forked from deutranium/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdepthFirstSearch.js
More file actions
44 lines (39 loc) · 772 Bytes
/
depthFirstSearch.js
File metadata and controls
44 lines (39 loc) · 772 Bytes
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
// Graph class for the Algorithm
class Graph {
constructor(v) {
this.V = v;
this.adj = Array(v);
for (let i = 0; i < v; ++i) {
this.adj[i] = [];
}
}
addEdge(v, w) {
this.adj[v].push(w);
}
DFSUtil(v, visited) {
visited[v] = true;
console.log(v + " ");
let vList = this.adj[v];
for (let n in vList) {
if (!visited[n]) this.DFSUtil(n, visited);
}
}
DFS(v) {
let visited = new Array(this.V);
this.DFSUtil(v, visited);
}
}
function main() {
let g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
console.log(
"The Following is Depth First Traversal " + "(Starting from vertex 2)"
);
g.DFS(2);
}
main();