-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.js
52 lines (45 loc) · 1.01 KB
/
graph.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (this.adjacencyList[vertex]) return;
this.adjacencyList[vertex] = [];
}
removeVertex(vertex) {
while (this.adjacencyList[vertex].length) {
const vtx = this.adjacencyList[vertex].pop();
this.removeEdge(vertex, vtx);
}
delete this.adjacencyList[vertex];
}
addEdge(vtx1, vtx2) {
this.adjacencyList[vtx1].push(vtx2);
this.adjacencyList[vtx2].push(vtx1);
}
removeEdge(vtx1, vtx2) {
this.adjacencyList[vtx1] = this.adjacencyList[vtx1].filter(
(vtx) => vtx !== vtx2
);
this.adjacencyList[vtx2] = this.adjacencyList[vtx2].filter(
(vtx) => vtx !== vtx1
);
}
}
const g = new Graph();
g.addVertex('A');
g.addVertex('B');
g.addVertex('C');
g.addVertex('D');
g.addEdge('A', 'B');
g.addEdge('B', 'D');
g.addEdge('B', 'C');
g.addEdge('A', 'C');
g.addEdge('C', 'D');
module.exports = g;
// console.log(g);
// A
// / \
// B ---- C
// \ /
// D