"Dijkstra is just BFS that grew up and learned to count money. Instead of a plain queue, it uses a priority queue — always expanding the cheapest-known node next. That one upgrade turns 'fewest hops' into 'lowest cost.'"
The Algorithm
Dijkstra finds the cheapest path from one source to every other node in a graph with non-negative weights. The machinery:
- Keep a tentative distance to every node, starting at 0 for the source and infinity for the rest.
- Put
(0, source)in a min-heap (priority queue). - Pop the node with the smallest tentative distance. Finalize it — its distance is now certain.
- Relax its neighbors: for each, if going through the just-finalized node is cheaper than its current tentative distance, update it and push the new distance to the heap.
- Repeat until the heap is empty.
Compare to BFS: same expand-the-frontier shape, but the frontier is a priority queue keyed by total cost instead of a plain FIFO queue. Dijkstra is, almost literally, BFS with a heap — the Heaps track and the Graphs track meeting in one algorithm.
Why Finalizing on Pop Is Safe
Here's the greedy insight that makes Dijkstra correct: when you pop the closest unfinalized node, its tentative distance is already its true shortest distance. Why? Every other path to it would have to go through some node that's still in the heap — and those are all farther than the one you just popped, and since weights are non-negative, detouring through a farther node can only add cost. So no cheaper path can ever appear. That's the whole proof, and it's also exactly why Dijkstra requires non-negative weights: a negative edge would let a 'farther' node secretly offer a cheaper route, breaking the guarantee — which is the cliffhanger for the next lesson.
Where It Runs the World
Dijkstra (and its heuristic-guided cousin A*) is the shortest-path algorithm in your GPS, in network routing protocols (OSPF computes least-cost routes between routers with it), in game pathfinding, in flight/transit planners. Any 'cheapest route through a weighted network with non-negative costs' is a Dijkstra. The priority queue you learned in the Heaps track is what makes it efficient — without a heap, repeatedly finding the cheapest frontier node would be O(V²) instead of O((V+E) log V).