-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.js
49 lines (40 loc) · 1011 Bytes
/
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
class Node {
constructor(label) {
this.label = label;
}
}
class Graph {
constructor() {
this.nodes = {}; // string: node
this.adjancyList = new Map(); // node: node[]
}
addNode(label) {
const node = new Node(label);
this.nodes[label] = node;
this.adjancyList.set(node, []);
}
addEdge(from, to) {
const fromNode = this.nodes[from];
const toNode = this.nodes[to];
if (!fromNode || !toNode) return;
this.adjancyList.set(fromNode, [...this.adjancyList.get(fromNode), toNode]);
}
print() {
const keys = this.adjancyList.keys();
for (const key of keys) {
console.log(
key.label + ' => ' + this.adjancyList.get(key).map((v) => v.label),
);
}
}
}
const graph = new Graph();
graph.addNode('a');
graph.addNode('b');
graph.addNode('c');
graph.addNode('d');
graph.addEdge('a', 'b');
graph.addEdge('a', 'c');
graph.addEdge('a', 'd');
graph.addEdge('b', 'd');
graph.print();