Dijkstra Shortest Path With Min Heap Typed

Compute single source shortest paths in a typed weighted graph using Dijkstra with a min heap.

TypescriptData Fetching

Code

snippet
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;
}