-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdfs.js
94 lines (77 loc) · 1.91 KB
/
dfs.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
const GraphBase = require('./graph-base');
const Stack = require('./ds/stack');
class DFS extends GraphBase {
constructor(numVertices = 0, numEdges = 0, startingPoint = 0) {
super(numVertices, numEdges);
this.startingPoint = startingPoint;
}
dfs() {
let stack = new Stack();
let Adj = this.getSimpleAdj();
let visited = [];
let vertex = [];
Adj.forEach((value, key) => {
visited[key] = false;
vertex.push(key);
});
let root = vertex[0];
stack.push(root);
let dfs_order = [];
while (!stack.isEmpty()) {
let node = stack.pop();
if (!visited[node]) {
dfs_order.push(node);
visited[node] = true;
}
for (let i = 0; i < Adj.get(node).length; i++) {
if (!visited[Adj.get(node)[i]]) {
stack.push(Adj.get(node)[i]);
}
}
}
return dfs_order;
}
// dfs for a transpose graph
dfsForTranspose() {
let stack = new Stack();
let Adj = this.getTransposeAdj();
let visited = [];
let vertex = [];
Adj.forEach((value, key) => {
visited[key] = false;
vertex.push(key);
});
let root = vertex[0];
stack.push(root);
let dfs_order = [];
while (!stack.isEmpty()) {
let node = stack.pop();
if (!visited[node]) {
dfs_order.push(node);
visited[node] = true;
}
for (let i = 0; i < Adj.get(node).length; i++) {
if (!visited[Adj.get(node)[i]]) {
stack.push(Adj.get(node)[i]);
}
}
}
return dfs_order;
}
}
// const g = new DFS(5)
// vertices = [0,1,2,3,4]
// for(let i=0;i<vertices.length;i++)
// {
// g.addVertex(vertices[i])
// }
// g.addEdge(1, 0);
// g.addEdge(0, 2);
// g.addEdge(2, 1);
// g.addEdge(0, 3);
// g.addEdge(3,4);
// g.addEdge(4,0);
// // console.log(g.adj)
// console.log(g.dfs())
module.exports = DFS;
//Adj -> Returns simple adj list; adj->more complex(with edges)