Sub topic 1
What a Cell Remembers: Defining the State
Prerequisites
This chapter assumes you can write Python with lists and nested loops. You should be able to index a 2D array as grid[i][j] by row and column, follow a recursive function, and read Big-O notation.
What a Cell Remembers
Grid DP starts with one sentence: "dp[i][j] is ..." That sentence is the state. It must name one quantity, such as a count, a minimum cost, or a length, for a precisely defined subproblem that ends (or starts) at cell (i, j).
Good examples:
dp[i][j]= number of right/down paths from(0, 0)to(i, j).dp[i][j]= minimum cost of reaching(i, j).
If you cannot finish the sentence, you have no recurrence yet. A vague state such as "the best so far" is the most common source of wrong answers.
From Moves to Recurrences
The moves a problem allows tell you which neighbors can lead into a cell. If moves go only right and down, (i, j) is reached from (i-1, j) or (i, j-1). You then combine those neighbors in the way the state requires:
| Goal | Combine with | Recurrence |
|---|---|---|
| Count paths | sum | `dp[i][j] = dp[i-1][j] + dp[i][j-1]` |
| Minimum cost | min, then add the cell | `dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + cost[i][j]` |
Base Cases, Edges, and Padding
Cells in row 0 or column 0 are missing a neighbor. You can handle this in one of two ways:
- Branch on
i == 0andj == 0. - Pad the table with an extra row and column filled with a neutral value: 0 for sums, infinity for minimums. Then seed one entry so the start cell comes out right.
def count_paths(m, n):
dp = [[0] * (n + 1) for _ in range(m + 1)]
dp[0][1] = 1 # seed so dp[1][1] becomes 1
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m][n]
print(count_paths(3, 3)) # 6Filling the Table in the Right Order
Every value a cell reads must already be computed. Right/down moves point up and left, so you fill row by row from the top and left to right within each row. If the dependencies point the other way, reverse both loops.
Exercise
Moves go only left and up, and the goal is the top-left cell. Starting from the bottom-right cell, which neighbors does dp[i][j] read, and in what order should the loops run?
Show answer
dp[i][j] reads dp[i+1][j] and dp[i][j+1]. Run i from m-1 down to 0 and j from n-1 down to 0, so the cells below and to the right are computed first.