-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweightedGraph.js
More file actions
51 lines (44 loc) · 1.09 KB
/
weightedGraph.js
File metadata and controls
51 lines (44 loc) · 1.09 KB
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
class WeightedGraph {
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.node);
}
delete this.adjacencyList[vertex];
}
addEdge(vtx1, vtx2, weight) {
this.adjacencyList[vtx1].push({ node: vtx2, weight });
this.adjacencyList[vtx2].push({ node: vtx1, weight });
}
removeEdge(vtx1, vtx2) {
this.adjacencyList[vtx1] = this.adjacencyList[vtx1].filter(
(vtx) => vtx.node !== vtx2
);
this.adjacencyList[vtx2] = this.adjacencyList[vtx2].filter(
(vtx) => vtx.node !== vtx1
);
}
}
const g = new WeightedGraph();
g.addVertex('A');
g.addVertex('B');
g.addVertex('C');
g.addVertex('D');
g.addEdge('A', 'B', 4);
g.addEdge('B', 'D', 6);
g.addEdge('B', 'C', 3);
g.addEdge('A', 'C', 1);
g.addEdge('C', 'D', 8);
console.log(g.adjacencyList);
// A
// 4 / \ 1
// B --3-- C
// 6 \ / 8
// D