Sub topic 1
What a Cell Remembers: Defining the State
Every grid dynamic programming (DP) solution starts with one sentence: "dp[i][j] is ...". If that sentence is vague, the recurrence, base cases, and fill order built on it will be wrong. This chapter covers how to write that sentence precisely.
Prerequisites
This chapter assumes you are comfortable with:
- Basic Python syntax, including lists and nested loops
- Two-dimensional arrays and row/column indexing (
grid[i][j]is rowi, columnj) - Recursion and function call stacks
- Big-O notation for time and space
The State Is a Promise
A DP state is a small set of values that identifies one subproblem. In most grid problems the state is a cell position (i, j). The table entry dp[i][j] stores the answer to that subproblem.
A good state definition answers three questions:
- Which subproblem? Usually "paths from the start to
(i, j)", or "paths from(i, j)to the goal". - What quantity? A count, a minimum cost, a maximum length, or a yes/no answer.
- Under what constraints? For example, "moving only right or down", or "the square must end at this corner".
For minimum-cost paths, a complete definition reads: dp[i][j] is the smallest sum of cell values over all right/down paths from (0, 0) to (i, j), including both endpoints.
Checking a Definition by Brute Force
You can test a state definition before you write any recurrence. Compute each entry directly from its meaning and look at the table. The code below enumerates every right/down path to each cell and records the cheapest one. It runs in exponential time, but it shows exactly what each entry promises.
def all_paths_to(i, j):
"""Every right/down path from (0, 0) to (i, j), as lists of cells."""
if i == 0 and j == 0:
return [[(0, 0)]]
paths = []
if i > 0:
paths += [p + [(i, j)] for p in all_paths_to(i - 1, j)]
if j > 0:
paths += [p + [(i, j)] for p in all_paths_to(i, j - 1)]
return paths
grid = [[1, 3, 1],
[1, 5, 1],
[4, 2, 1]]
dp = [[min(sum(grid[r][c] for r, c in path) for path in all_paths_to(i, j))
for j in range(3)] for i in range(3)]
for row in dp:
print(row)
# [1, 4, 5]
# [2, 7, 6]
# [6, 8, 7]The answer to the full problem is dp[2][2] = 7. Later chapters compute this table efficiently. The meaning of each entry stays the same.
Common Errors in State Design
| Mistake | Example | Consequence |
|---|---|---|
| Ambiguous endpoint | "cost of a path through `(i, j)`" | Subproblems overlap in unclear ways, and no clean recurrence exists |
| Missing inclusion rule | Unclear whether `grid[i][j]` is counted | Answers are off by one cell's value |
| State too small | Tracking only `(i, j)` when two walkers move at once | Different situations collapse into one entry |
| Wrong anchor | "largest square containing `(i, j)`" | The entry can't be built from its neighbors |
Exercise
For the maximal-square problem, why is "dp[i][j] = side of the largest all-ones square containing cell (i, j)" a poor state, and what definition works better?
Show answer
Many squares of different positions contain the cell, so the entry doesn't relate cleanly to its neighbors' entries. Define dp[i][j] as the side of the largest all-ones square whose bottom-right corner is (i, j). Each such square extends squares ending at the cells above, to the left, and diagonally up-left, which gives a direct recurrence.
Exercise
In the brute-force table above, dp[1][1] = 7. Which path produces it, and does the definition count grid[1][1]?
Show answer
The path (0,0) → (1,0) → (1,1) has cost 1 + 1 + 5 = 7. The path through (0,1) costs 1 + 3 + 5 = 9. The definition includes both endpoints, so grid[1][1] = 5 is counted.