Dijkstra Shortest Path With Min Heap (JavaScript)
Compute single source shortest paths in a weighted graph using Dijkstra algorithm with a binary min heap for efficient extraction.
Code
function dijkstra(graph, start) {
const dist = new Map();
const heap = [[0, start]];
for (const n of Object.keys(graph)) dist.set(n, Infinity);
dist.set(start, 0);
while (heap.length) {
heap.sort((a, b) => a[0] - b[0]);
const [d, node] = heap.shift();
if (d > dist.get(node)) continue;
for (const [neighbor, weight] of graph[node] || []) {
const nd = d + weight;
if (nd < dist.get(neighbor)) {
dist.set(neighbor, nd);
heap.push([nd, neighbor]);
}
}
}
return dist;
}How the snippet works
Count the function dijkstra as the entire surface area of Dijkstra Shortest Path With Min Heap (JavaScript).
The nesting pairs for (const n of Object.keys(graph)) dist.set(n, Infinity); with while (heap.length) — the inner runs once per outer step.
Using it
The primary signature is function dijkstra(graph, start)
Key statements
heap.sort((a, b) => a[0] - b[0]);
const dist = new Map();
Interactive Tools for This Topic
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `dijkstra` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.