-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfs.js
59 lines (53 loc) · 1.63 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
var DFS = {
dfs:function(startNode , finishNode){
s = [] ;
s.push(startNode) ;
var parent = new Map() ;
parent.set(startNode , -1) ;
visitedNodes = [] ;
while(s.length != 0){
var topNode = s[s.length - 1] ;
console.log(s.pop()) ;
visitedNodes.push(topNode);
if(topNode == finishNode){
DFS.dfssetPath(parent , visitedNodes ,startNode , finishNode);
console.log("It has ended")
return ;
}
var neighbor = topNode.neighbors ;
console.log(neighbor);
for(var i = 0 ; i < neighbor.length ; i++){
if(neighbor[i].visited == false){
neighbor[i].visited = true ;
s.push(neighbor[i]);
parent.set(neighbor[i] , topNode) ;
}
}
}
animate("No Path found") ;
enable();
},
dfssetPath : async function (parent , visitedNodes , startNode , finishNode){
await DFS.updateVisited(visitedNodes);
crawl = parent.get(finishNode) ;
while(crawl != -1){
await sleep(1) ;
if(crawl != startNode && crawl != finishNode && crawl != null)
crawl.state = 'p' ;
crawl = parent.get(crawl) ;
if(crawl == startNode)
break;
console.log(crawl)
}
enable() ;
return "Path found" ;
},
updateVisited : async function (visitedNodes){
for (var i = 0 ; i < visitedNodes.length ; i++){
if(visitedNodes[i].state != 's' && visitedNodes[i].state != 'f' && visitedNodes[i].state != 'p' ){
await sleep(1) ;
visitedNodes[i].state = 'd' ;
}
}
}
}