-
Notifications
You must be signed in to change notification settings - Fork 0
/
DeapthFirstSearch.js
44 lines (32 loc) · 946 Bytes
/
DeapthFirstSearch.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
//ref: https://mgechev.github.io/javascript-algorithms/graphs_searching_dfs.js.html
const stack = require('./stack');
function dfs(graph, start, end){
let nodeStack = new stack();
let visited = [];
nodeStack.push(start);
visited[start] = true;
while(nodeStack.top() >= 0){
let tmpNode = nodeStack.pop();
if(end === tmpNode){
console.log("path found");
return true;
}
for(let i=0; i<=graph[tmpNode].length - 1; i++){
if(graph[tmpNode][i] === 1 && !visited[i]){
nodeStack.push(i);
}
}
visited[tmpNode] = true;
console.log("path does not exists");
return false;
}
}
//sample graph
const graph = [[1, 1, 0, 0, 1, 0],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 0],
[0, 0, 1, 0, 1, 1],
[1, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0]];
//check if there exists a path in graph between start and end
dfs(graph, 1, 5);