-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijkstra.js
73 lines (62 loc) · 1.9 KB
/
dijkstra.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
var DijkstraAlgo = {
dijkstra : async function(start , finish){
visitedNodes = [] ;
q = [] ;
start.distance = 0 ;
var parent = new Map() ;
parent.set(start , -1) ;
q.push(start);
console.log("q" , q) ;
while(q.length != 0){
q.sort(cmp) ;
var closestNode = q[0] ;
q.shift() ;
visitedNodes.push(closestNode) ;
if(closestNode == finish){
var r = DijkstraAlgo.setPath(parent , visitedNodes ,startNode , finishNode);
return parent ;
}
var neighbor = closestNode.neighbors ;
for (var i = 0 ; i < neighbor.length ; i++){
if(neighbor[i].distance > (closestNode.distance + 1)){
parent.set(neighbor[i] , closestNode) ;
neighbor[i].distance = closestNode.distance + 1 ;
q.push(neighbor[i]) ;
}
}
}
animate("No Path found") ;
enable();
} ,
setPath : async function (parent , visitedNodes ,startNode , finishNode){
await DijkstraAlgo.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) ;
}
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' ;
}
}
return new Promise(function(resolve , reject){
setTimeout(() => {
const check = true ;
if(check){
resolve();
}
else{
reject();
}
}, 1000);
});
}
};