Sub topic 2
From Moves to Recurrences
This chapter assumes you can write nested loops over a 2D Python list, read Big-O notation, and follow a recursive definition. It also assumes you already have a state definition from the previous chapter, such as "dp[i][j] is the number of ways to reach cell (i, j)." The task here is to turn the problem's allowed moves into a formula that computes each dp[i][j] from other entries.
The Core Idea: Reverse the Moves
A problem statement usually describes moves going forward: "from a cell you may step right or down." A recurrence looks backward. It asks which cells could have led to (i, j) in one move. Those cells are the predecessors of (i, j).
To find them, apply each move in reverse. If a move adds (di, dj) to your position, then the predecessor through that move is (i - di, j - dj).
| Forward move | Offset `(di, dj)` | Predecessor of `(i, j)` |
|---|---|---|
| Right | `(0, 1)` | `(i, j - 1)` |
| Down | `(1, 0)` | `(i - 1, j)` |
| Diagonal down-right | `(1, 1)` | `(i - 1, j - 1)` |
| Knight-style `(1, 2)` | `(1, 2)` | `(i - 1, j - 2)` |
Every path that ends at (i, j) has a last move, and that last move came from exactly one predecessor. This fact is what makes a recurrence work: you split all paths into groups by their last move, solve each group using the predecessor's entry, and combine the results.
A Five-Step Derivation
You can derive most grid recurrences with the same five steps.
- List the moves as offsets
(di, dj). - Reverse them to get the predecessor cells.
- Pick the combine operator that matches the question: sum, min, max, or logical OR.
- Decide where the cost goes: on the cell you enter, on the move you make, or both.
- Check that each predecessor's entry means the same thing as
dp[i][j], with no hidden history the state fails to capture.
Step 3: The Combine Operator Comes From the Question
The question you are answering decides how the predecessor values get combined. The moves do not.
| Question | Combine | Recurrence shape (right/down moves) |
|---|---|---|
| How many paths reach the cell? | sum | `dp[i][j] = dp[i-1][j] + dp[i][j-1]` |
| What is the cheapest path to the cell? | min | `dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + cost[i][j]` |
| What is the most value you can collect? | max | `dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + value[i][j]` |
| Can the cell be reached at all? | OR | `dp[i][j] = dp[i-1][j] or dp[i][j-1]` |
Each operator also has an identity, the value that leaves a combination unchanged. The identity for sum is 0, for min it is inf, for max it is -inf, and for OR it is False. A missing or invalid predecessor should contribute the identity. The chapter on base cases uses this fact to pad tables safely.
Step 4: Where the Cost Attaches
When a problem has costs, they can sit on cells, on moves, or on both. The general form for a min-cost problem is:
dp[i][j] = cost[i][j] + min over moves m of (dp[i - di][j - dj] + w(m))
The cell cost cost[i][j] is paid once, outside the min, because every path into (i, j) pays it whatever its last move was. The move cost w(m) sits inside, because it depends on which predecessor you came from. A common mistake is to add the predecessor's cell cost again inside the min. That cost is already part of dp[pred], so adding it again counts it twice.
A Recurrence Built From a Move List
Since the recurrence comes directly from the move list, you can write code that takes the moves as data. This function counts paths for any set of forward moves where di >= 0, dj >= 0, and the two are not both zero. Those conditions ensure every predecessor appears earlier in row-by-row order. The chapter on fill order explains why that matters.
def count_paths(m, n, moves):
dp = [[0] * n for _ in range(m)]
dp[0][0] = 1
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
continue
total = 0
for di, dj in moves:
pi, pj = i - di, j - dj
if 0 <= pi < m and 0 <= pj < n:
total += dp[pi][pj]
dp[i][j] = total
return dp[m - 1][n - 1]
print(count_paths(3, 3, [(0, 1), (1, 0)])) # 6
print(count_paths(3, 3, [(0, 1), (1, 0), (1, 1)])) # 13Adding the diagonal move adds one predecessor term, dp[i-1][j-1], and increases the count from 6 to 13. The loop body never changes. Only the move list does.
The same pattern handles move costs. In this version each move has a weight, cell costs are added once, and the combine operator is min:
def min_cost(grid, moves):
m, n = len(grid), len(grid[0])
INF = float('inf')
dp = [[INF] * n for _ in range(m)]
dp[0][0] = grid[0][0]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
continue
best = INF
for (di, dj), w in moves:
pi, pj = i - di, j - dj
if 0 <= pi < m and 0 <= pj < n:
best = min(best, dp[pi][pj] + w)
dp[i][j] = best + grid[i][j]
return dp[m - 1][n - 1]
grid = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
print(min_cost(grid, [((0, 1), 0), ((1, 0), 0)])) # 7
print(min_cost(grid, [((0, 1), 0), ((1, 0), 0), ((1, 1), 1)])) # 6With a diagonal move that costs 1, the best route is (0,0) → (1,0) → (2,1) → (2,2), with cell costs 1 + 1 + 2 + 1 plus 1 for the diagonal, a total of 6.
Step 5: When the State Is Too Small
A recurrence is valid only if the best (or total) answer at (i, j) can be built from predecessor entries without knowing anything else about how those predecessors were reached. When a move's legality or cost depends on history, the two-index state is not enough, and you need to add a dimension.
Take the rule "you may not make the same move twice in a row" with right/down moves. Whether a "right" step into (i, j) is allowed depends on the previous move, and dp[i][j] does not record it. The fix is to add the last move to the state:
R[i][j]= number of valid paths reaching(i, j)whose last move was right.D[i][j]= number of valid paths reaching(i, j)whose last move was down.
The recurrences now cross between the two tables:
R[i][j] = D[i][j-1](a right step must follow a down step)D[i][j] = R[i-1][j](a down step must follow a right step)
The answer is R[m-1][n-1] + D[m-1][n-1]. The same technique covers "at most k turns," "pay extra when changing direction," and similar rules: put the missing history into the state, then derive the recurrence again with the five steps.
Common Errors
| Error | Symptom | Fix |
|---|---|---|
| Using successors instead of predecessors | Reads cells not computed yet; answers are zero or wrong | Reverse each move: `(i - di, j - dj)` |
| Wrong combine operator | Counts come out as costs, or min where max was needed | Pick the operator from the question, not the moves |
| Adding cell cost inside the `min` | Costs are double-counted | Add `cost[i][j]` once, outside the combine |
| Ignoring a move-dependent rule | Answer includes illegal paths | Add the needed history to the state |
| Identity value is wrong | `min` with `0` padding always returns 0 | Use `inf` for min, `-inf` for max, `0` for sum |
Exercise
A robot moves on an m×n grid using right (0, 1), down (1, 0), and down-left (1, -1). Write the counting recurrence for dp[i][j], and explain why plain row-by-row, left-to-right filling still works.
Show answer
The predecessors are (i, j-1), (i-1, j), and (i-1, j+1), so dp[i][j] = dp[i][j-1] + dp[i-1][j] + dp[i-1][j+1], counting only predecessors inside the grid. The down-left move has di = 1, so its predecessor is always in the previous row, which row-by-row filling has already finished. The only same-row predecessor is (i, j-1), which lies to the left and is computed before (i, j).
Exercise
Each cell has a value to collect, moves are right and down, and a right step costs 2 while a down step is free. Write the recurrence for the maximum net value collected on arrival at (i, j).
Show answer
dp[i][j] = value[i][j] + max(dp[i][j-1] - 2, dp[i-1][j]). The cell value is added once outside the max, and the move cost is subtracted inside, only on the branch that uses the right move. Missing predecessors contribute -inf.
Exercise
With right/down moves, a path may make at most one turn, where a turn is a change between right and down. Which extra state dimensions do you need, and why is dp[i][j] alone not enough?
Show answer
You need the last move direction and whether the single turn has already been used, for example dp[i][j][d][t] with d in {right, down} and t in {0, 1}. Whether the next move counts as a turn depends on the previous direction, and whether a turn is allowed depends on whether one was already taken. dp[i][j] records neither, so it cannot tell legal extensions from illegal ones.