Dijkstra's algorithm
◈ 4 cardsGreedy EXTRACT-MIN + RELAX for nonnegative weights, O((V+E) lg V) with a heap. Knows the negative-edge counterexample.
Dijkstra: greedy shortest paths for nonnegative weights
Dijkstra solves single-source shortest paths when all edge weights are , and it is faster than Bellman-Ford. It maintains a set of vertices whose final distance is known and a min-priority queue keyed by v.d:
INITIALIZE-SINGLE-SOURCE(G, s); insert all vertices into .- While :
u = EXTRACT-MIN(Q); add to ; relax every out-edge , callingDECREASE-KEYwhenv.ddrops.
Each vertex is extracted once, and at that moment its distance is final. With a binary heap: extractions and key decreases at each give . A linear array scan gives (best for dense graphs); a Fibonacci heap gives .
Worked correctness (the squeeze)
When is extracted, let be the first vertex not in on a shortest path, and its predecessor. When entered we relaxed , so (convergence). Then
where: because is on a shortest path to and all weights are nonnegative (a prefix is no longer than the whole); is the upper-bound property; because EXTRACT-MIN chose over . Everything is squeezed equal, so .
Why negative edges break it — the counterexample
The chain relies on nonnegativity. With a negative edge, a longer path can be cheaper, and the greedy commitment is wrong. Concrete case: edges (weight 2), (weight 5), (weight ). Dijkstra extracts first with and freezes it — but the true shortest path is . Use Bellman-Ford when weights can be negative.
Worked example
On the CLRS Fig 22.6 graph (all nonnegative; vertices ) Dijkstra from gives distances .