Dynamic Programming on Graphs
Many graph algorithms are dynamic programs: the subproblem is the best value reachable under a restricted resource — intermediate vertices allowed, edges allowed, or a topological prefix — and edge relaxation is the DP transition. We frame Floyd–Warshall as the archetype ( all-pairs shortest paths), Bellman–Ford as a DP over path length (the at-most--stops variant), DAG-DP in topological order (), and Warshall's transitive closure as the boolean analog.
╌╌╌╌
The Graphs module's Shortest Paths lesson introduced three algorithms (Dijkstra, Bellman–Ford, Floyd–Warshall) and remarked that one operation, relaxation, underlies them all. The Principles of Dynamic Programming lesson then distilled DP into optimal substructure plus overlapping subproblems. This lesson connects the two ideas with a single thesis: many graph algorithms are dynamic programs, and relaxation is the DP transition.
The pattern is always the same. We define a subproblem as the best value
obtainable using a restricted resource, and we grow the resource one unit at a
time. The resource
is whatever we ration:
- the set of intermediate vertices a path may pass through (Floyd–Warshall);
- the number of edges a path may use (Bellman–Ford, -stops);
- a topological prefix of an acyclic graph (DAG-DP);
- a subset of vertices already visited (Held–Karp, the Bitmask DP lesson).
Relaxing an edge , testing whether routing through improves the
current estimate for , is the over choices in a DP recurrence.
Under this framing, is there a path?
, what is the cheapest path?
, and how many shortest paths are there?
all become the same exercise: pick the resource,
write the recurrence, choose an evaluation order that respects the
dependencies.1
Floyd–Warshall: intermediate vertices as the resource
Number the vertices . Restrict which vertices a path is allowed to pass through internally, and relax that restriction one vertex at a time.
The base case is if the edge exists, if , and otherwise, since no intermediate vertices are allowed, so only direct edges count. The induction is the core of the method.
The lemma is a verbatim DP transition, route through or don't:
Because depends only on , and the two cells it reads in row/column are unchanged when or , we can drop the index and update the matrix in place. This yields the entire algorithm in three nested loops with outermost:
- 1; on diagonal, else
- 2for to do
- 3for to do
- 4for to do
- 5if then
- 6
- 7for reconstruction
- 8return
The triple loop is time and space, independent of the edge count, which is what makes Floyd–Warshall the method of choice for dense graphs where we want every pair at once.2
For a worked example, take four vertices with the weight matrix (rows are sources, where no direct edge exists):
Each level admits one more intermediate vertex. Allowing vertex () fixes : the direct entry was , but is not yet improved — rather becomes through vertex , and . Allowing vertex () sets and . Allowing vertex () improves to and to . The last level () routes through vertex to drop further to and to . Reading off gives every pairwise shortest distance at once.
Path reconstruction uses a matrix (above) initialized to for each edge: whenever routing through wins, the first hop out of toward becomes the first hop toward . To rebuild a path, follow . (A matrix storing the last vertex before is the symmetric alternative.) The practice problem Find the City With the Smallest Number of Neighbors at a Threshold Distance is Floyd–Warshall verbatim: compute all-pairs distances, then count for each city how many others lie within the threshold.
Bellman–Ford: edges as the resource
Floyd–Warshall rations intermediate vertices. Bellman–Ford rations edges, which makes it a single-source DP over path length.
A walk of at most edges to is either a walk of at most edges to , or such a walk to some predecessor followed by the edge :
Each round is one full sweep of edge relaxations, the same relaxation primitive from the Shortest Paths lesson, now indexed by a layer . Because a shortest path in a graph with no negative cycle is simple, it uses at most edges, so is the answer: after rounds the table converges. If one more round still relaxes some edge, a path of edges beats every shorter one, which can only happen along a negative cycle, so that extra relaxation is the standard negative-cycle test.3 The cost is sweeps of edges, .
The layered view pays off directly when the problem caps the number of edges. Cheapest Flights Within K Stops asks for the cheapest route using at most stops, i.e. at most edges. That is just : run exactly Bellman–Ford rounds, no more.
A concrete Cheapest Flights Within K Stops instance shows why the cap matters. Take cities with directed flights (cost ), (cost ), (cost ), (cost ), and the much cheaper two-leg detour competing against the direct-ish . Ask for the cheapest route with at most stop, that is at most edges, so we run exactly rounds, each relaxing against the frozen previous layer:
| layer | ||||
|---|---|---|---|---|
Round reaches the one-edge neighbors and . Round reaches two ways — and — and keeps . The answer is , using exactly edges (one stop). A cheaper -edge route, had one existed, would be invisible here precisely because we stopped after rounds: the cap is enforced by the round count, and freezing before round is what prevents from being reached in a single sweep through both edges.
DAG-DP: a topological prefix as the resource
When the graph is acyclic, the resource becomes trivial to ration: process vertices in topological order. A topological order lists every vertex after all of its predecessors, so by the time we reach , every for an incoming edge is already final. The recurrence has no cycles, so a single pass suffices, with no convergence over rounds and no over layers.
- 1
- 2for all ;
- 3for each in topological order do
- 4for each edge do
- 5if thenuse for longest path
- 6
- 7return
Each vertex and edge is touched once, so DAG-DP runs in , faster than Dijkstra and immune to negative weights, because acyclicity replaces the non-negativity that Dijkstra needs. The longest path problem, NP-hard in general graphs, is just as easy on a DAG: swap for . Acyclicity is what makes the difference.4
In the figure, is reached by via versus via ; the
keeps the through- edge (in acc), and because and were
finalized before in topological order, one forward sweep settles it.
Counting paths uses the same order. To count all paths in a DAG, set and accumulate over incoming edges in topo order. To count shortest paths in a weighted graph that may have cycles (Number of Ways to Arrive at Destination), process vertices in non-decreasing distance order (the order Dijkstra finalizes them, which is a topological order of the shortest-path DAG) and carry a parallel count:
The distance DP finds the best value; the count DP, evaluated in the same order, tallies how many ways achieve it.
Warshall's transitive closure: the boolean analog
Replace shortest distance
with is there any path
, and with
, and Floyd–Warshall becomes Warshall's transitive-closure
algorithm. Let be true iff is reachable from using
intermediate vertices in :
Same triple loop, same , same in-place collapse of the index; only
the semiring changed (booleans under or/and instead of reals under min/plus).
Course Schedule IV is this very problem: prerequisites form a DAG, and each query
is course a prerequisite of course ?
is a lookup in the reachability
matrix .
Held–Karp: a subset as the resource
The resource need not be a single number. In Held–Karp bitmask TSP (the Bitmask DP lesson), the subproblem is = the cheapest path starting at the origin, visiting exactly the vertex set , and ending at ; the transition relaxes over the last hop . The rationed resource is the subset of visited vertices, grown one vertex per layer, the same skeleton as Floyd–Warshall, with subsets in place of intermediate-vertex levels. Shortest Path Visiting All Nodes is the unweighted cousin: a BFS over states, where the mask is again the resource. The same framing scales from a single scalar resource up to an exponential subset.
Choosing the framing
All four are DP, but the right resource depends on the graph:
- Floyd–Warshall: dense, all-pairs, negative edges allowed; time, space. The default when you need every pair.
- Dijkstra: sparse graphs with non-negative weights; , which beats when .
- Bellman–Ford: single-source with negative edges, negative-cycle detection, or an edge-count cap (-stops); .
- DAG-DP: acyclic graphs; , handles negative weights and even longest paths, because topological order removes the need to iterate to convergence.
The algebraic view and its descendants
The unification in this lesson is an
instance of an algebraic fact. Floyd–Warshall, Warshall's closure, and even the
path-counting variant are all the same algorithm over different semirings. A
semiring supplies a that combines alternatives and a
that
concatenates a path in sequence: for shortest paths , for reachability
, for path counting , for widest-path / bottleneck
routing . Replace the operators and the triple loop computes the
corresponding closure without any other change. This is the algebraic path
problem, developed by Backhouse and Carré (1975) and by Lehmann (1977), and it
explains why
cheapest
, is there any
, and how many
are the same
exercise: one program parameterized by a semiring.5
The same all-pairs closure connects to linear algebra through matrix
multiplication over the semiring (the min-plus
or tropical
product). All-pairs shortest paths equals the -th tropical power of the
weight matrix, computable by repeated squaring in — slower than
Floyd–Warshall's , but the connection underlies the theory of
subcubic all-pairs shortest paths. Williams (2014) gave the first truly
subcubic APSP, running in ; whether a genuinely
polynomially-faster () algorithm exists is a central open
question, tied by fine-grained complexity to the (min,+)-matrix-multiplication and
Boolean-matrix-multiplication conjectures.
Held and Karp's subset DP for TSP (Held and Karp, 1962, J. SIAM) remains, sixty
years on, the fastest known exact TSP algorithm in the worst case at
time — no algorithm with a better exponential base is known, which
indicates how hard exact TSP is. On the practical side, the DAG shortest
path with a topological order underlies critical-path scheduling
(PERT/CPM): the longest path through a task-dependency DAG is the minimum project
completion time, and it is computed by exactly the variant of DAG-Relax
above. And the layered Bellman–Ford view — relax against the previous layer,
snapshotting each round — is the shape of the Viterbi algorithm for hidden
Markov models, where each layer
is a time step and the DP finds the most likely
state sequence.
Takeaways
- Many graph algorithms are dynamic programs. The subproblem is the best value under a restricted resource (intermediate vertices, edges, a topological prefix, or a visited subset), and edge relaxation is the DP transition.
- Floyd–Warshall is the archetype: , route through or don't, collapsing in place to time, space; negative edges OK, and flags a negative cycle.
- Bellman–Ford is a DP over path length, for at-most- edges; rounds converge, an extra relaxation detects a negative cycle, and capping at solves Cheapest Flights Within K Stops ().
- DAG-DP processes vertices in topological order for an single pass, shortest or longest path, and counting (shortest) paths by carrying a count alongside the distance.
- Warshall's transitive closure is the boolean Floyd–Warshall (), giving reachability, exactly Course Schedule IV.
- The resource can be a subset (Held–Karp / bitmask TSP), unifying scalar shortest paths with exponential-state DP under one frame.
Footnotes
- Erickson, Ch. — Dynamic Programming: the DP recipe is to define the subproblem, write the recurrence, and evaluate in an order respecting the dependency DAG. ↩
- CLRS, Ch. 23 — All-Pairs Shortest Paths (§23.2): Floyd–Warshall's intermediate-vertex recurrence, in-place evaluation, and negative-cycle detection via . ↩
- CLRS, Ch. 22 — Single-Source Shortest Paths: Bellman–Ford relaxes all edges times; a further relaxation reveals a negative cycle. ↩
- Skiena, § — Shortest Paths / DP: shortest and longest paths on a DAG in by relaxing edges in topological order; longest path is NP-hard only in general graphs. ↩
- Backhouse & Carré (1975) and Lehmann (1977) on the algebraic path problem: Floyd–Warshall, transitive closure, and path counting are one closure algorithm over different semirings (, , ). See Williams (2014, STOC) for subcubic APSP via min-plus matrix products, and Held & Karp (1962, J. SIAM 10) for the exact-TSP subset DP. ↩
╌╌ END ╌╌