forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
48 lines (38 loc) · 1.49 KB
/
Copy pathindex.js
File metadata and controls
48 lines (38 loc) · 1.49 KB
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
function dijkstra(g, source) {
/* initially, all distances are infinite and all predecessors are null */
for(let n in g.nodes)
g.nodes[n].distance = Infinity;
/* predecessors are implicitly null */
source.distance = 0;
let counter = 0;
/* set of unoptimized nodes, sorted by their distance (but a Fibonacci heap
would be better) */
let q = new BinaryMinHeap(g.nodes, "distance");
let node;
/* get the node with the smallest distance */
/* as long as we have unoptimized nodes */
while(q.min() != undefined) {
/* remove the latest */
node = q.extractMin();
node.optimized = true;
/* no nodes accessible from this one, should not happen */
if(node.distance == Infinity)
throw "Orphaned node!";
/* for each neighbour of node */
for(let e in node.edges) {
if(node.edges[e].target.optimized)
continue;
/* look for an alternative route */
let alt = node.distance + node.edges[e].weight;
/* update distance and route if a better one has been found */
if (alt < node.edges[e].target.distance) {
/* update distance of neighbour */
node.edges[e].target.distance = alt;
/* update priority queue */
q.heapify();
/* update path */
node.edges[e].target.predecessor = node;
}
}
}
}