Memra

Dijkstra's algorithm

◈ 4 cards

Greedy 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:

  1. INITIALIZE-SINGLE-SOURCE(G, s); insert all vertices into .
  2. While : u = EXTRACT-MIN(Q); add to ; relax every out-edge , calling DECREASE-KEY when v.d drops.

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 .

51039212467sd = 0td = 8xd = 14yd = 5zd = 7S = {s, y}; next extract z (d 7).
Dijkstra on the exercise graph (s, t, x, y, z = 0–4) after extracting s and then y. S = {s, y} is settled; the highlighted edges are the three just relaxed out of y, which pulled t to 8, z to 7 and x to 14. The next EXTRACT-MIN takes z (d = 7) — and by the squeeze argument that 7 is already final.
25−4sd = 0ud = 2vd = 5δ(s,u) = 5 − 4 = 1, not 2.
Why nonnegativity is a premise. Dijkstra extracts u first with u.d = 2 and never revisits it, but the route s→v→u costs 5 + (−4) = 1. The negative edge breaks δ(s,y) ≤ δ(s,u) in the squeeze — a longer path is now cheaper — so the greedy commitment is simply wrong. Reach for Bellman-Ford instead.
NORMAL ~/memra/learn/comp-372/dijkstra utf-8 LF