Skip to content

Commit 495ce69

Browse files
authored
Added the javascript implementation
Added the javascript implementation
1 parent 952c92d commit 495ce69

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Dijkstra's /Javascript

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
function dijkstra(g, source) {
2+
/* initially, all distances are infinite and all predecessors are null */
3+
for(var n in g.nodes)
4+
g.nodes[n].distance = Infinity;
5+
/* predecessors are implicitly null */
6+
7+
source.distance = 0;
8+
var counter = 0;
9+
/* set of unoptimized nodes, sorted by their distance (but a Fibonacci heap
10+
would be better) */
11+
var q = new BinaryMinHeap(g.nodes, "distance");
12+
13+
var node;
14+
/* get the node with the smallest distance */
15+
/* as long as we have unoptimized nodes */
16+
17+
while(q.min() != undefined) {
18+
/* remove the latest */
19+
node = q.extractMin();
20+
node.optimized = true;
21+
22+
/* no nodes accessible from this one, should not happen */
23+
if(node.distance == Infinity)
24+
throw "Orphaned node!";
25+
26+
/* for each neighbour of node */
27+
for(e in node.edges) {
28+
if(node.edges[e].target.optimized)
29+
continue;
30+
31+
/* look for an alternative route */
32+
var alt = node.distance + node.edges[e].weight;
33+
34+
/* update distance and route if a better one has been found */
35+
if (alt < node.edges[e].target.distance) {
36+
37+
/* update distance of neighbour */
38+
node.edges[e].target.distance = alt;
39+
40+
/* update priority queue */
41+
q.heapify();
42+
43+
/* update path */
44+
node.edges[e].target.predecessor = node;
45+
}
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)