-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.js
More file actions
85 lines (62 loc) · 1.62 KB
/
Copy pathgraph.js
File metadata and controls
85 lines (62 loc) · 1.62 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const Queue = require('./queue.js');
class Graph {
constructor(noOfVertices) {
this.noOfVertices = noOfVertices;
this.AdjList = new Map();
}
addVertex(v) {
this.AdjList.set(v, []);
}
addEdge(v, w) {
// get the list for vertex v and put the vertex w denoting edge between v and w
this.AdjList.get(v).push(w);
// since graph is undirected, add an edge from w to v also
this.AdjList.get(w).push(v);
}
print() {
const keys = this.AdjList.keys();
for (const i of keys) {
const values = this.AdjList.get(i);
let conc = '';
for (const j of values) {
conc += j + ' ';
}
console.log(i + ' -> ' + conc);
}
}
// Breadth First Traversal
bfs(startingNode) {
const visited = {};
const q = new Queue();
visited[startingNode] = true;
q.enqueue(startingNode);
while (!q.isEmpty()) {
const getQueueElement = q.dequeue();
console.log(getQueueElement);
const getList = this.AdjList.get(getQueueElement);
for (const i in getList) {
const neigh = getList[i];
if (!visited[neigh]) {
visited[neigh] = true;
q.enqueue(neigh);
}
}
}
}
// Depth First Traversal
dfs(startingNode) {
const visited = {};
this.DFSUtil(startingNode, visited);
}
DFSUtil(vert, visited) {
visited[vert] = true;
console.log(vert);
const getNeighbours = this.AdjList.get(vert);
for (const i in getNeighbours) {
const getElement = getNeighbours[i];
if (!visited[getElement]) {
this.DFSUtil(getElement, visited);
}
}
}
}