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
53 lines (44 loc) · 1.46 KB
/
Copy pathindex.js
File metadata and controls
53 lines (44 loc) · 1.46 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
49
50
51
52
53
/* eslint-disable no-unused-vars */
/* eslint-disable guard-for-in */
/* eslint-disable require-jsdoc */
function dijkstra(g, source) {
/* initially, all distances are infinite and all predecessors are null */
for (const n in g.nodes) {
g.nodes[n].distance = Infinity;
}
/* predecessors are implicitly null */
source.distance = 0;
const counter = 0;
/* set of unoptimized nodes, sorted by their distance (but a Fibonacci heap
would be better) */
const 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 new Error('Orphaned node!');
}
/* for each neighbour of node */
for (const e in node.edges) {
if (node.edges[e].target.optimized) {
continue;
}
/* look for an alternative route */
const 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;
}
}
}
}