File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments