function dijkstra(graph: Graph, source: Node) {const dist = new Map([[source, 0]]);
const open = new MinHeap([[0, source]]);
while (open.size > 0) {const [distance, node] = open.pop(); // smallest dist
if (distance > dist.get(node)!) continue;
for (const [neighbor, weight] of graph.edges(node)) {const newDistance = distance + weight;
if (newDistance >= (dist.get(neighbor) ?? Infinity)) continue;
dist.set(neighbor, newDistance);
open.push([newDistance, neighbor]);
}
}
return dist;
}
Source A gets distance 0; every other node is at ∞.
Understanding Dijkstra
The idea
Dijkstra grows a set of settled nodes whose shortest distance is final. Each round it takes the unsettled node with the smallest tentative distance, settles it, and relaxes its edges: if going through it makes a neighbour closer, the neighbour's tentative distance and parent are updated.
It works because with non-negative weights no later path can beat the smallest tentative distance in the heap. The tree of parent edges is the shortest-path tree from the source to every node it reached.
The four stages
Complexity
Versus its siblings
Pseudocode
DIJKSTRA(graph, source)
dist[source] ← 0; heap ← {(0, source)}while heap not empty
(distance, node) ← pop the smallest; skip if stale
for each edge node–neighbour with its weight
if distance + weight < dist[neighbour]: dist[neighbour] ← distance + weight; parent[neighbour] ← node; push (distance + weight, neighbour)
When to use
Pitfalls
History
Edsger Dijkstra found the algorithm in 1956 while thinking about the shortest way between Rotterdam and Groningen, and published it in 1959. The heap-based version everyone uses came later; with Fibonacci heaps Fredman and Tarjan reached O(E + V log V) in 1984, still the best bound for sparse graphs.