-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweightedGraph.js
More file actions
33 lines (28 loc) · 825 Bytes
/
weightedGraph.js
File metadata and controls
33 lines (28 loc) · 825 Bytes
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
class WeightedGraph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) {
this.adjacencyList[vertex] = [];
}
}
addEdge(vertex1, vertex2, weight) {
this.adjacencyList[vertex1].push({ node: vertex2, weight });
this.adjacencyList[vertex2].push({ node: vertex1, weight }); // If undirected
}
printGraph() {
for (let vertex in this.adjacencyList) {
console.log(vertex, '->', this.adjacencyList[vertex].map(e => `${e.node}(${e.weight})`).join(', '));
}
}
}
const wg = new WeightedGraph();
wg.addVertex('A');
wg.addVertex('B');
wg.addVertex('C');
wg.addEdge('A', 'B', 5);
wg.addEdge('B', 'C', 2);
wg.addEdge('A', 'C', 10);
wg.printGraph();
console.log(wg.adjacencyList)