Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

DP as Shortest Paths in a DAG

The subproblem graph, Bellman’s principle, and when DP cannot work.

Every dynamic program you have written is a path computation in a graph you never drew: its vertices are subproblems, its edges are options, and its loop order is a topological order. Drawing that graph explains why DP is fast, why Bellman–Ford, Dijkstra and Floyd–Warshall are dynamic programs, which objectives break the method, and why "pure" DP algorithms for some problems provably cannot be beaten, unless they stop being pure.

What you’ll learn

  • Build the subproblem DAG of a DP, read its running time as O(∣V∣+∣E∣)O(\abs V + \abs E), and read its value as an optimal path or a path count.
  • State Bellman's principle of optimality, prove it for monotone compositions, and repair the standard failures (negative products, simple paths).
  • Handle cyclic dependencies with a decreasing parameter (Bellman–Ford, Floyd–Warshall), an order discovered on the fly (Dijkstra), or a fixed-point iteration.
  • Explain the semiring view and the Viterbi algorithm, and what tropical-circuit lower bounds say, and do not say, about pure DP algorithms.

The subproblem graph

DPVerticesEdgesQuestion about paths
Climbing stairs0,1,…,n0, 1, \dots, ni→i+1i \to i + 1 and i→i+2i \to i + 2How many paths from 0 to nn?
Grid walkThe cellsTo the right and lower neighbors, weighted by the cost of the cell enteredShortest path between the corners
Edit distancePairs (i,j)(i, j)Right (insert), down (delete), diagonal (match costs 0, substitute 1)Shortest path from (0,0)(0, 0) to (n,m)(n, m)
LCSPairs (i,j)(i, j)Right and down (worth 0), diagonal on a match (worth 1)Longest path from (0,0)(0, 0) to (n,m)(n, m)
House robberPrefixes 0,…,n0, \dots, ni→i−1i \to i - 1 (worth 0) and i→i−2i \to i - 2 (worth a[i−1]a[i-1])Longest path from nn to a base state
The graph of edit distance and LCS is the edit graph: every corner-to-corner path is an alignment of the two strings.

The DAG view gives the running time for free. A pass in topological order handles each vertex and each edge once, so a DP costs O(∣V∣+∣E∣)O(\abs V + \abs E) plus the work per edge. Any topological order is a valid fill order, and memoized recursion finds one by itself: it is a depth-first search of the subproblem graph from the original problem.

Check your understanding

A memoized recursion evaluates a DP top-down. In what order do its subproblems finish, that is, return their values?

  1. In a topological order of the dependencies: each subproblem finishes after every subproblem it reads
  2. In decreasing order of their values
  3. In the order in which the original problem lists them
  4. In no particular order; only the final answer is well defined
Show the answer

A. In a topological order of the dependencies: each subproblem finishes after every subproblem it reads

The recursion is a depth-first search of the subproblem DAG. A call returns only after every call it makes has returned or hit the memo, so the finishing order (a DFS postorder) lists each subproblem after its dependencies: an order a bottom-up loop could use, restricted to the reachable subproblems.

Bellman's principle of optimality

The principle fails when the cost of the rest of a path does not determine what is best for the whole. Two standard failures, and their repairs:

  • Non-monotone composition. Maximize the product of edge weights when some are negative. Multiplying by a negative number reverses the order, so the best continuation may come from the smallest product so far. Repair: keep both the largest and the smallest value per vertex, the trick behind "maximum product subarray".
  • Path-dependent feasibility. For the longest simple path in a graph with cycles, the rest of the path must avoid the vertices already used, so "the best path from tt" is not a well-defined subproblem. On the square q−r−t−s−qq - r - t - s - q, a longest simple path from qq to tt is q,r,tq, r, t, yet its piece from qq to rr is not a longest simple path from qq to rr: q,s,t,rq, s, t, r is longer. Gluing longest pieces (q,s,t,rq, s, t, r, then r,q,s,tr, q, s, t) even revisits vertices. Repair: put the set of used vertices into the state, a bitmask DP of exponential size.
python
def max_product_path(order, edges, s, t):
    """Largest product of edge weights over s -> t paths in a DAG (weights may be negative)."""
    hi = {v: float('-inf') for v in order}   # largest product from s to v
    lo = {v: float('inf') for v in order}    # smallest product from s to v
    hi[s] = lo[s] = 1
    for u in order:                          # a topological order
        if hi[u] == float('-inf'):
            continue                         # u is not reachable from s
        for v, w in edges.get(u, []):
            cands = (hi[u] * w, lo[u] * w)   # a negative w swaps the roles
            hi[v] = max(hi[v], *cands)
            lo[v] = min(lo[v], *cands)
    return hi[t]

edges = {'s': [('t', 4), ('a', 3), ('x', 1)], 'x': [('a', -5)], 'a': [('t', -2)]}
print(max_product_path(['s', 'x', 'a', 't'], edges, 's', 't'))   # 10: s, x, a, t

Keeping only the largest product per vertex returns 4 here: at aa it keeps 3 and forgets −5-5, which the last edge turns into (−5)(−2)=10(-5)(-2) = 10. The pair (largest, smallest) is a sufficient state; the largest alone is not. Checked against brute force on random DAGs.

Check your understanding

For which objective does a DP over the vertices of a DAG that keeps one best value per vertex give wrong answers?

  1. The cheapest path, with arbitrary real weights
  2. The widest path: maximize the smallest capacity along the path
  3. The largest product of edge weights, when some weights are negative
  4. The number of paths from ss to each vertex
Show the answer

C. The largest product of edge weights, when some weights are negative

Sums and bottlenecks compose monotonically, and counting adds over all options. A product with a negative factor reverses the order, so the smallest product so far can become the largest; the state must keep both extremes.

When the dependencies have cycles

On a graph with cycles, "the shortest path to vv" depends on itself through the cycle, and a memoized recursion either loops forever or, if cut off, returns wrong values. Three repairs, all classics:

  • Add a parameter that decreases. Let dk(v)d_k(v) be the length of a shortest walk from ss to vv with at most kk edges. Then dk(v)=min⁡(dk−1(v), min⁡(u,v)dk−1(u)+w(u,v))d_k(v) = \min\big(d_{k-1}(v),\ \min_{(u, v)} d_{k-1}(u) + w(u, v)\big) reads only layer k−1k - 1: a DP on a layered DAG. Without negative cycles, shortest paths have at most n−1n - 1 edges, so dn−1d_{n-1} is final. This is Bellman–Ford, O(nm)O(nm) time. If one more layer still improves something, a negative cycle is reachable and walks around it get ever cheaper: there is no optimum, and the principle of optimality, which presupposes one, has nothing to say.
  • Discover the order. With non-negative weights, the unsettled vertex with the smallest tentative distance is final, so settling vertices by increasing distance is a topological order of the shortest-path DAG, found on the fly: Dijkstra's algorithm. A negative edge breaks this order.
  • Restrict the intermediate vertices. In Floyd–Warshall, dk(i,j)d_k(i, j) is the shortest i→ji \to j path whose intermediate vertices are among the first kk: again a DP with a decreasing parameter, O(n3)O(n^3) time for all pairs.
python
def bellman_ford(n, edges, s):
    """d[v] after round k = length of a shortest walk from s to v with at most k edges."""
    INF = float('inf')
    d = [INF] * n
    d[s] = 0
    for k in range(1, n):                  # layer k of the layered DAG
        new = d[:]
        for u, v, w in edges:
            if d[u] + w < new[v]:
                new[v] = d[u] + w
        if new == d:
            break                          # nothing changed: final
        d = new
    for u, v, w in edges:                  # one more layer: still improving?
        if d[u] + w < d[v]:
            raise ValueError('negative cycle reachable from s')
    return d

On the widget's "negative" graph below, with A–F numbered 0–5, it returns 0, 1, 4, 4, 6, 6; on the graph with a negative cycle it raises the error. Updating d in place instead of copying it is also correct and often converges in fewer rounds.

Semirings, Viterbi and the limits of pure DP

Nothing in the DAG pass needs min and +. Any two operations ⊕\oplus (combine alternatives) and ⊗\otimes (extend a path) that form a semiring, with ⊗\otimes distributing over ⊕\oplus, work: (min⁡,+)(\min, +) for shortest paths, (max⁡,+)(\max, +) for longest, (+,×)(+, \times) for counting, (or, and) for reachability, and (max⁡,×)(\max, \times) for the most probable path. The Graphs lesson Paths in DAGs tabulates them.

The best-known instance is the Viterbi algorithm (Viterbi, 1967). A hidden Markov model with KK hidden states emits observations o1,…,oTo_1, \dots, o_T; the most probable sequence of hidden states is a best path, in (max⁡,×)(\max, \times), through a trellis DAG with one vertex per (time, state) pair:

δt(j)=max⁡i δt−1(i) aij bj(ot),\delta_t(j) = \max_{i}\ \delta_{t-1}(i)\, a_{ij}\, b_j(o_t),

where aija_{ij} are the transition and bjb_j the emission probabilities. The trellis has TKTK vertices and (T−1)K2(T - 1)K^2 edges, so decoding takes O(TK2)O(TK^2) time; logarithms turn the products into sums, to avoid underflow. Replacing max by a sum gives the forward algorithm, which computes the total probability of the observations.

The bound is about the model, not the problem. Williams (STOC 2014) computes all-pairs shortest paths in n3/2Ω(log⁡n)n^3 / 2^{\Omega(\sqrt{\log n})} time by leaving the model: polynomials from circuit complexity turn a min-plus product into a small number of rectangular matrix products over F2\mathbb{F}_2. Likewise, Dijkstra's order by distance amounts to sorting, and Duan, Mao, Mao, Shu and Yin (STOC 2025) broke that "sorting barrier" for directed single-source shortest paths: deterministic O(mlog⁡2/3n)O(m \log^{2/3} n) time in the comparison-addition model, faster than Dijkstra on sparse graphs.

Key takeaways

  • Every DP is a path problem on its subproblem DAG: shortest paths for min-plus, longest for max-plus, path counts for sum-product. It runs in O(∣V∣+∣E∣)O(\abs V + \abs E) in any topological order, and memoized recursion finds such an order by depth-first search.
  • Bellman's principle holds when a path's cost is a monotone function of the cost of its remainder. It fails for non-monotone compositions (products with negative weights: keep the minimum and the maximum) and for path-dependent constraints (simple paths: keep the visited set).
  • Cyclic dependencies need a decreasing parameter (Bellman–Ford over the number of edges, Floyd–Warshall over the allowed intermediate vertices), an order discovered on the fly (Dijkstra, with non-negative weights), or a fixed-point iteration (value iteration). A reachable negative cycle leaves no optimum at all.
  • Pure DPs are tropical circuits: Kerr's Ω(n3)\Omega(n^3) bound makes Floyd–Warshall optimal in that model, while Williams's n3/2Ω(log⁡n)n^3/2^{\Omega(\sqrt{\log n})} algorithm shows that the bound does not hold for algorithms that use other operations.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the edit graph of strings aa and bb, with a vertex for each pair of prefix lengths (i,j)(i, j), what is the edit distance?

  1. The number of paths from (0,0)(0, 0) to (n,m)(n, m)
  2. The length of a shortest path from (0,0)(0, 0) to (n,m)(n, m), where horizontal and vertical edges cost 1 and a diagonal edge costs 0 on a match and 1 otherwise
  3. The length of a longest path from (0,0)(0, 0) to (n,m)(n, m) in which matching diagonals are worth 1
  4. The number of diagonal edges on any path from (0,0)(0, 0) to (n,m)(n, m)
Show the answer

B. The length of a shortest path from (0,0)(0, 0) to (n,m)(n, m), where horizontal and vertical edges cost 1 and a diagonal edge costs 0 on a match and 1 otherwise

Each corner-to-corner path is an alignment: a horizontal step inserts a letter of bb, a vertical step deletes a letter of aa, and a diagonal step matches or substitutes. The path's cost is its number of edits, so the edit distance is the shortest path; the LCS is the longest path when only matching diagonals count.

Question 2

Which semiring, used over the trellis of a hidden Markov model, finds the most probable sequence of hidden states?

  1. (+,×)(+, \times): the forward algorithm
  2. (max⁡,×)(\max, \times), or (max⁡,+)(\max, +) on log-probabilities: the Viterbi algorithm
  3. (min⁡,+)(\min, +) on the probabilities themselves
  4. (or, and): reachability
Show the answer

B. (max⁡,×)(\max, \times), or (max⁡,+)(\max, +) on log-probabilities: the Viterbi algorithm

A state sequence's probability is a product along its trellis path, and the best sequence maximizes it, so alternatives combine by max and steps by multiplication; logarithms turn this into a longest path with sums. Summing instead of maximizing gives the forward algorithm, the total probability of the observations.

Question 3

Bellman–Ford as a DP computes dk(v)d_k(v), the shortest walks with at most kk edges, for k=1,…,n−1k = 1, \dots, n - 1. If one more layer still improves some d(v)d(v), what follows?

  1. More rounds are needed; keep going until nothing changes
  2. A negative cycle is reachable from ss, so some vertices have no shortest path
  3. The graph has more than nn vertices
  4. Dijkstra's algorithm would succeed instead
Show the answer

B. A negative cycle is reachable from ss, so some vertices have no shortest path

Without a negative cycle, every vertex has a shortest walk that is a simple path with at most n−1n - 1 edges, so dn−1d_{n-1} is final and no further layer improves it. An improvement exhibits a cheaper walk with nn edges, which repeats a vertex and contains a negative cycle; going around it again lowers the cost further, so no optimum exists.

Question 4

Kerr's Ω(n3)\Omega(n^3) lower bound for (min⁡,+)(\min, +) circuits means that…

  1. no algorithm computes all-pairs shortest paths in o(n3)o(n^3) time
  2. every algorithm that only takes minima and sums of the weights needs Ω(n3)\Omega(n^3) operations for a min-plus matrix product, so Floyd–Warshall is optimal among such algorithms
  3. Floyd–Warshall is the fastest algorithm for sparse graphs
  4. dynamic programming is always slower than Dijkstra's algorithm
Show the answer

B. every algorithm that only takes minima and sums of the weights needs Ω(n3)\Omega(n^3) operations for a min-plus matrix product, so Floyd–Warshall is optimal among such algorithms

The bound holds for tropical circuits, which model pure dynamic programs. Williams's n3/2Ω(log⁡n)n^3/2^{\Omega(\sqrt{\log n})} algorithm uses other operations and is asymptotically faster, so no unconditional n3n^3 bound for every algorithm follows.

Further reading

  • R. Bellman, Dynamic Programming (Princeton University Press, 1957).
  • A. J. Viterbi, "Error bounds for convolutional codes and an asymptotically optimum decoding algorithm," IEEE Transactions on Information Theory 13(2) (1967), 260–269.
  • L. R. Kerr, The effect of algebraic structure on the computational complexity of matrix multiplications, PhD thesis, Cornell University (1970).
  • S. Jukna, "Lower bounds for tropical circuits and dynamic programs," Theory of Computing Systems (2015).
  • R. Williams, "Faster all-pairs shortest paths via circuit complexity," STOC 2014.