Dijkstra's algorithm
medium 22 minDijkstra's algorithm finds the shortest distance from one source to every node of a graph whose edge weights are non-negative.
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
Pop the closest, call it final, relax its neighbours: a ripple of settled distances spreading out from the source.
Drop a stone in a still pond. The ripple reaches nearby points first and far points later, never the other way round. Dijkstra is that ripple: it always finishes the closest unfinished place next, so by the time the wave touches a node, no faster route to it can exist, as long as no road runs downhill into negative cost.
Cheat sheet
- Solves
- single-source shortest paths, weights at least 0
- Heap entry
- (distance, node)
- Relax
- if dist[u] + w < dist[v]: update dist, prev, push
- Final when
- popped and not stale
- Stale test
- d > dist[u]: skip
- Time (heap)
- O((V + E) log V)
- Time (array)
- O(V²), dense graphs
- Space
- O(V + E)
- Negative weights
- Bellman-Ford, O(V·E)
Spot it when you see
- Shortest, cheapest, fastest or least risky route with non-negative costs.
- A weighted graph or grid where BFS hop counts are not enough.
- Network delay, signal propagation time, travel time from one source.
- Path cost that never improves when extended: maximum probability, minimum effort.
Tricks that stick
- GREEDY: Get the minimum from the heap, Relax its edges, Extract the next minimum, Each neighbour checked, Distance updated, Yet visited? Skip.
- Dijkstra is BFS with a min-heap instead of a queue: closest first, not oldest first.
- Settle on POP, never on PUSH.
- Distance first in the tuple: (d, node).
- Path: follow prev backwards, then reverse.
Do not forget
- Using it with negative weights.
- Marking nodes visited when pushed instead of when popped.
- Forgetting to skip stale heap entries.
- Pushing (node, distance) so the heap orders by name.
- Returning when the target is pushed rather than popped.
- Adding two-way edges in one direction only.