Bellman-Ford & DAG shortest paths
◈ 4 cardsBellman-Ford handles negative weights and detects negative cycles in O(VE); DAG-SHORTEST-PATHS does it in Θ(V+E) via topological order.
Bellman-Ford: relax everything, |V|−1 times
Bellman-Ford solves single-source shortest paths even when edges are negative, and it detects a reachable negative cycle (in which case no finite answer exists). The algorithm:
INITIALIZE-SINGLE-SOURCE(G, s).- Repeat times: relax every edge .
- One more pass: if any edge can still be relaxed (
v.d > u.d + w(u,v)), returnFALSE— a negative cycle is reachable. Otherwise returnTRUE.
Why passes? A shortest path in a graph with no negative cycle is simple — at most edges. By the path-relaxation property, after pass every shortest path using edges has its correct value. After passes, all of them do.
Running time is : each of the passes scans all edges.
Worked correctness of the negative-cycle check
Suppose after the passes some edge still satisfies v.d > u.d + w(u,v). If there were no negative cycle, every reachable vertex would already hold and the triangle inequality would forbid any further relaxation — contradiction. Conversely, sum the relaxed inequalities around a cycle : . The -terms cancel (each vertex appears once on each side), leaving . So a still-relaxable edge means — a negative cycle.
DAG shortest paths: one pass in topological order
If the graph is a DAG there are no cycles at all (hence no negative cycles), so you don't need passes — one pass suffices. Topologically sort the vertices, then relax each vertex's out-edges in that order. Because a topological order processes every predecessor of before , all paths into are accounted for by the time you relax out of it. This runs in and handles negative weights freely (great for PERT / critical-path scheduling — negate weights for longest path).
Worked example
On the CLRS Fig 22.4 graph (vertices , several negative edges, no negative cycle) Bellman-Ford from yields distances . Add one more strongly negative edge to create a negative cycle and the algorithm reports it.