Skip to content

Commit c8e2c2d

Browse files
committed
Graphs Complete Course
1 parent 748b54d commit c8e2c2d

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

8. Graphs/index.js

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
class Graph {
2+
constructor() {
3+
this.adjacencyList = {};
4+
}
5+
6+
addVertex(vtx) {
7+
if (!this.adjacencyList[vtx]) {
8+
this.adjacencyList[vtx] = [];
9+
return true;
10+
}
11+
return false;
12+
}
13+
14+
addEdge(vtx1, vtx2) {
15+
if (this.adjacencyList[vtx1] && this.adjacencyList[vtx2]) {
16+
this.adjacencyList[vtx1].push(vtx2);
17+
this.adjacencyList[vtx2].push(vtx1);
18+
return true;
19+
}
20+
return false;
21+
}
22+
23+
removeEdge(vtx1, vtx2) {
24+
if (this.adjacencyList[vtx1] && this.adjacencyList[vtx2]) {
25+
this.adjacencyList[vtx1] = this.adjacencyList[vtx2].filter(
26+
(v) => v !== vtx2
27+
);
28+
29+
this.adjacencyList[vtx2] = this.adjacencyList[vtx2].filter(
30+
(v) => v !== vtx1
31+
);
32+
return true;
33+
}
34+
return false;
35+
}
36+
37+
removeVertex(vtx) {
38+
if (!this.adjacencyList[vtx]) return undefined;
39+
40+
for (let neighbor of this.adjacencyList[vtx]) {
41+
this.adjacencyList[neighbor] = this.adjacencyList[neighbor].filter(
42+
(v) => v !== vtx
43+
);
44+
}
45+
46+
delete this.adjacencyList[vtx];
47+
return this;
48+
}
49+
}
50+
51+
let g = new Graph();
52+
// ----------------
53+
// g.addVertex("A");
54+
// g.addVertex("B");
55+
// g.addEdge("A", "B");
56+
// ----------------
57+
58+
// ----------------
59+
// g.addVertex("A");
60+
// g.addVertex("B");
61+
// g.addVertex("C");
62+
// g.addEdge("A", "B");
63+
// g.addEdge("B", "C");
64+
// g.addEdge("C", "A");
65+
// console.log(g);
66+
// g.removeEdge("A", "B");
67+
// console.log(g);
68+
// ----------------
69+
70+
g.addVertex("A");
71+
g.addVertex("B");
72+
g.addVertex("C");
73+
g.addVertex("D");
74+
g.addEdge("A", "B");
75+
g.addEdge("A", "C");
76+
g.addEdge("A", "D");
77+
g.addEdge("B", "D");
78+
g.addEdge("C", "D");
79+
console.log(g);
80+
g.removeVertex("D");
81+
console.log(g);

0 commit comments

Comments
 (0)