Intuition
Pour water into a network of pipes at the start node, where each pipe’s weight is how long water takes to flow through it. The water reaches nodes in order of their distance. The moment it first reaches a node, that’s the shortest time to get there, and nothing arriving later can beat it.
Dijkstra’s algorithm simulates that wave. Instead of BFS’s queue, it uses a priority queue that always hands back the closest waiting node.
How it works
- Set the start’s distance to 0 and every other node’s to ∞. Put the start in the priority queue.
- Take out the closest node. If it was already settled, skip it: that was an old, longer entry.
- Settle it: its distance is now final.
- For each neighbour, check whether going through this node is shorter than its best distance so far. If it is, update the distance and add the neighbour to the queue. This check is called relaxing the edge.
- Repeat until the queue is empty.
The dark edges in the figure record which node each distance came through. Following them back from any node traces its shortest path.
Why it works
When a node is the closest unsettled one, any other route to it would have to pass through some unsettled node that is already at least as far away, and with non-negative weights the rest of that route can only add more. So its distance can’t improve later, and settling it is safe.
Complexity
With a binary heap, each edge can push one entry, and each push or pop costs O(log V), so the total is O((V + E) log V). For dense graphs, a simple array scan for the minimum gives O(V²).
Common mistakes
- Negative weights. A settled distance might later shrink, and Dijkstra won’t notice. Use Bellman–Ford for graphs with negative edges.
- Not skipping stale entries. The queue can hold several entries for one node; only the first one popped is real.
- Stopping too early. To get every distance, run until the queue is empty. To find one target, you may stop when the target is settled.
Check yourself
Check yourself
In the figure's small-town graph, how far is G from A?
A → C costs 2, C → F costs 9, and F → G costs 1: 12 in total. The route through B and D reaches F at 12 and G at 13, so it loses.
Check yourself
Why can't Dijkstra's algorithm handle negative edge weights?
Settling assumes no later path can be shorter. A negative edge found later could make one shorter, but the node is already final.
Sources
- Edsger W. Dijkstra, “A note on two problems in connexion with graphs,” Numerische Mathematik 1 (1959): 269–271.
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, section 24.3 (3rd edition).
Finished this page?
Your list