-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdirected-graph.js
More file actions
63 lines (53 loc) · 1.23 KB
/
Copy pathdirected-graph.js
File metadata and controls
63 lines (53 loc) · 1.23 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
52
53
54
55
56
57
58
59
60
61
62
63
class DirectedGraph {
constructor() {
this.list = {};
}
addVertex(node) {
if (this.list[node] === undefined) {
this.list[node] = new Set();
}
else {
return "node already exist";
}
}
addEdge(node1, node2) {
if (this.list[node1] === undefined) {
this.addVertex(node1);
}
if (this.list[node2] === undefined) {
this.addVertex(node2);
}
this.list[node1].add(node2);
}
removeVertex(node) {
if (this.list[node] === undefined) {
return "Vertex undefined";
}
for (let o of Object.keys(this.list)) {
this.list[o].delete(node)
}
delete this.list[node];
}
removeEdge(node1, node2) {
if (this.list[node1] === undefined || this.list[node2] === undefined) {
return "Invalid vertex";
}
else {
this.list[node1].delete(node2);
}
}
print() {
console.log(this.list)
}
}
let ug = new DirectedGraph();
ug.addVertex("A");
ug.addVertex("B");
ug.addVertex("C");
ug.print();
ug.addEdge("A", "B");
ug.print();
ug.addEdge("A", "C");
ug.print();
ug.removeVertex("B");
ug.print();