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;
}Report a problem with this exampleOpens a pre-filled issue on GitHub.