-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlineDijkstra.js
71 lines (61 loc) · 2.07 KB
/
lineDijkstra.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
function lineDijkstra(startNode, finishNode , lines , nodes){
startNode.distance = 0 ;
q = [] ;
q.push(startNode) ;
var parent = new Map() ;
parent.set(startNode , -1);
while(q.length != 0){
q.sort(cmp);
var closestNode = q[0] ;
q.shift() ;
var neighbor = closestNode.neighbors;
for(var i = 0 ; i < neighbor.length ; i++){
if(neighbor[i].distance > closestNode.distance+getWeight(neighbor[i],closestNode,lines)){
neighbor[i].distance = closestNode.distance+getWeight(neighbor[i],closestNode,lines);
q.push(neighbor[i]);
parent.set(neighbor[i] , closestNode);
}
}
}
for(var i = 0 ; i < nodes.length ; i++){
console.log(nodes[i].distance);
}
updateLines(parent ,finishNode, lines);
return parent ;
}
function cmp(nodeA ,nodeB){
return nodeA.distance - nodeB.distance ;
}
function getWeight(p1 , p2 ,lines){
for(var i =0 ; i < lines.length ; i++){
if(lines[i].p1.x == p1.x && lines[i].p1.y == p1.y && lines[i].p2.x == p2.x && lines[i].p2.y == p2.y){
return lines[i].weight ;
}
if(lines[i].p2.x == p1.x && lines[i].p2.y == p1.y && lines[i].p1.x == p2.x && lines[i].p1.y == p2.y){
return lines[i].weight ;
}
}
}
function getLine(p1 , p2 , lines){
if(p1 && p2){
for(var i =0 ; i < lines.length ; i++){
if(lines[i].p1.x == p1.x && lines[i].p1.y == p1.y && lines[i].p2.x == p2.x && lines[i].p2.y == p2.y){
return lines[i];
}
if(lines[i].p2.x == p1.x && lines[i].p2.y == p1.y && lines[i].p1.x == p2.x && lines[i].p1.y == p2.y){
return lines[i];
}
}
}
}
async function updateLines(parent , finishNode , lines){
var crawl = finishNode;
while(crawl != -1){
await sleep(1000) ;
var l = getLine(crawl , parent.get(crawl) , lines);
if(l) {
l.state = 'p' ;
}
crawl = parent.get(crawl) ;
}
}