Dijkstra Shortest Path With Min Heap Typed
Compute single source shortest paths in a typed weighted graph using Dijkstra with a min heap.
Code
function dijkstra(graph: Map<string, [string, number][]>, start: string): Map<string, number> {
const dist = new Map<string, number>();
const heap: [number, string][] = [[0, start]];
for (const n of graph.keys()) 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.get(node) ?? []) {
const nd = d + weight;
if (nd < dist.get(neighbor)!) { dist.set(neighbor, nd); heap.push([nd, neighbor]); }
}
}
return dist;
}What the code does
Count the function dijkstra as the entire surface area of Dijkstra Shortest Path With Min Heap Typed.
Iteration is nested: for (const n of graph.keys()) dist.set(n, Infinity); frames the pass, while (heap.length) does the per-item step.
Using it
The main signature reads function dijkstra(graph: Map<string, [string, number][]>, start: string)
Key statements
heap.sort((a, b) => a[0] - b[0]);
for (const [neighbor, weight] of graph.get(node) ?? []) {
const nd = d + weight;
if (nd < dist.get(neighbor)!) { dist.set(neighbor, nd); heap.push([nd, neighbor]); }
}
const dist = new Map<string, number>();
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `dijkstra` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.