Skip to content

Commit b2abfc2

Browse files
committed
adding Graph data structure
1 parent 4b47c06 commit b2abfc2

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Data Structures/Graph/Graph.js

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
2+
class Graph {
3+
4+
constructor() {
5+
this.adjacencyMap = {}
6+
}
7+
8+
addVertex(v) {
9+
this.adjacencyMap[v] = [];
10+
}
11+
12+
containsVertex(vertex) {
13+
return typeof (this.adjacencyMap[vertex]) !== "undefined"
14+
}
15+
16+
addEdge(v, w) {
17+
let result = false
18+
if (this.containsVertex(v) && this.containsVertex(w)) {
19+
this.adjacencyMap[v].push(w);
20+
this.adjacencyMap[w].push(v);
21+
result = true
22+
}
23+
return result
24+
}
25+
26+
27+
28+
printGraph() {
29+
let keys = Object.keys(this.adjacencyMap);
30+
for (let i of keys) {
31+
let values = this.adjacencyMap[i];
32+
let vertex = "";
33+
for (let j of values)
34+
vertex += j + " ";
35+
console.log(i + " -> " + vertex);
36+
}
37+
}
38+
39+
}
40+
41+
42+
const example = () => {
43+
let g = new Graph()
44+
g.addVertex(1)
45+
g.addVertex(2)
46+
g.addVertex(3)
47+
g.addEdge(1, 2)
48+
g.addEdge(1, 3)
49+
g.printGraph()
50+
}

0 commit comments

Comments
 (0)