-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph.js
54 lines (46 loc) · 1.33 KB
/
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
50
51
52
53
54
class Graph {
constructor(){
this.adjacentList = {};
this.numberOfNodes = 0;
}
//for each vertex add an array that will hold adjacent vertex/vertices
addVertex(node){
this.adjacentList[node] = [];
this.numberOfNodes++;
}
addEdge(node1, node2){
//since undirected so we have to push bothways
this.adjacentList[node1].push(node2);
this.adjacentList[node2].push(node1);
}
//optional - displays the adjacency list thus formed
displayCollections(){
const allNodes = Object.keys(this.adjacentList);
for(let node of allNodes){
let nodeCollections = this.adjacentList[node];
let connections = "";
let vertex;
for(vertex of nodeCollections){
connections += vertex+ " ";
}
console.log(node + "-->"+connections);
}
}
}
const myGraph = new Graph();
myGraph.addVertex('0');
myGraph.addVertex('1');
myGraph.addVertex('2');
myGraph.addVertex('3');
myGraph.addVertex('4');
myGraph.addVertex('5');
myGraph.addVertex('6');
myGraph.addEdge('3','1');
myGraph.addEdge('3','4');
myGraph.addEdge('4','2');
myGraph.addEdge('4','5');
myGraph.addEdge('1','2');
myGraph.addEdge('1','0');
myGraph.addEdge('0','2');
myGraph.addEdge('6','5');
myGraph.displayCollections();