-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphAdjMatrix.js
140 lines (111 loc) · 3.23 KB
/
GraphAdjMatrix.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
//Graph Representation using ---- Adjacency Matrix
class Graph {
constructor() {
this.adjMatrix = [];
this.verticesList = [];
}
addVertex(node) {
this.verticesList.push(node);
}
createAdjacenyMatrix() {
let vlen = this.verticesList.length;
if (vlen !== 0) {
for (let i = 0; i < vlen + 1; i++) {
let row = [];
for (let i = 0; i < vlen + 1; i++) {
row.push(0);
}
this.adjMatrix.push(row);
}
}
}
addEdge(x, y) {
if (this.verticesList.length !== 0 && this.adjMatrix.length === 0) {
this.createAdjacenyMatrix();
this.addNodes(x, y);
} else {
this.addNodes(x, y);
}
}
addNodes(x, y) {
this.adjMatrix[x][y] = 1;
this.adjMatrix[y][x] = 1;
}
displayAdjacencyMatrix() {
return this.adjMatrix;
}
breadthFirstSearch(node){
// traversedList - contains all those nodes whose neighouring nodes are visited once completly
let traversedList = [];
let len = this.adjMatrix.length;
// Assigning false values to all nodes never visited
let visited = [];
for(let i=0; i < len;i++ ){
visited[i] = false;
}
let queue = [];
queue.push(node);
visited[node] = true;
while(queue.length > 0){
let current = queue.shift();
for(let i = 0; i < len; i++){
if(this.adjMatrix[current][i] === 1){
if(!visited[i]){
queue.push(i);
visited[i] = true;
}
}
}
traversedList.push(current);
}
return traversedList;
}
depthFirstSearch(node){
let traversedList = [];
let stack = [];
let visited = [];
let len = this.adjMatrix.length;
for(let i=0; i < len;i++ ){
visited[i] = false;
}
// marking starting node as visited and traversed
visited[node] = true;
traversedList.push(node);
while( stack.length > 0 || node){
let current = node;
for(let i=0; i < len+1;i++){
if(this.adjMatrix[node][i] === 1 && !visited[i]){
stack.push(node);
visited[i] = true;
traversedList.push(i);
node = i;
break;
}
}
if(node === current){
node = stack.pop();
}
}
return traversedList;
}
}
let graph = new Graph();
graph.addVertex('1');
graph.addVertex('2');
graph.addVertex('3');
graph.addVertex('4');
graph.addVertex('5');
graph.addVertex('6');
graph.addVertex('7');
graph.addEdge('1', '2');
graph.addEdge('1', '3');
graph.addEdge('1', '4');
graph.addEdge('2', '3');
graph.addEdge('3', '4');
graph.addEdge('3', '5');
graph.addEdge('4', '5');
graph.addEdge('5', '6');
graph.addEdge('5', '7');
//console.log(graph.displayAdjacencyMatrix());
//console.log(graph.breadthFirstSearch(5));
console.log(graph.depthFirstSearch(4));