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 precise, the recurrence, the base cases, and the fill order usually follow without much trouble. If it is vague, the bugs you hit later trace back to it. This chapter is about writing that sentence well. It covers what a cell should store, how to check that the stored value is enough, and when one cell coordinate is not enough and the state needs another dimension.
Prerequisites
This chapter assumes you can already:
- Read and write basic Python, including lists, nested loops, and list comprehensions.
- Index a two-dimensional list as
grid[row][col], with row 0 at the top. - Follow a recursive function and reason about its call stack.
- Read Big-O notation such as O(m·n).
You do not need any earlier exposure to dynamic programming. Recurrences, base cases, and fill order each get their own chapter later. Here the focus is only on what a table entry means.
The State Is a Question
A DP state is a small, named subproblem. In a grid, the natural subproblem is attached to a cell: "what is the answer if the walk stops here?" The table entry dp[i][j] stores the answer to that question for cell (i, j).
A useful way to write the state is as a full sentence with four parts:
- The quantity: a count, a minimum cost, a maximum length, a true/false flag.
- The objects being measured: paths, squares, edit sequences.
- The anchor: how the subproblem is tied to
(i, j). It might start there, end there, or have its corner there. - The rules: which moves are allowed and which cells are usable.
For the classic problem of moving only right or down from the top-left corner, a complete state reads:
dp[i][j] = the number of distinct right/down paths that start at (0, 0) and end at (i, j).
The final answer is then one particular entry, dp[m-1][n-1]. Not every problem works that way. Sometimes the answer is the maximum over all entries, which is how the maximal-square problem later in the tutorial works.
Checking the Meaning with Brute Force
Before you write any recurrence, you can confirm that a state definition means what you think it means by answering its question directly with brute force. The code below fills a table where each entry is computed independently by exhaustive search, straight from the sentence above.
def paths_to(i, j, ti, tj):
"""Count right/down move sequences from (i, j) that reach (ti, tj)."""
if i > ti or j > tj:
return 0
if (i, j) == (ti, tj):
return 1
return paths_to(i + 1, j, ti, tj) + paths_to(i, j + 1, ti, tj)
def state_table(m, n):
# Each entry answers the state's question on its own, by exhaustive search.
return [[paths_to(0, 0, i, j) for j in range(n)] for i in range(m)]
for row in state_table(3, 4):
print(row)
# [1, 1, 1, 1]
# [1, 2, 3, 4]
# [1, 3, 6, 10]This is exponential and you would never ship it. It still does two useful things. It produces a reference table to test a fast solution against, and it forces you to make the definition concrete enough to compute. If you cannot write a brute-force version of the question, the state is probably not yet well defined.
Anchoring: "Ending Here" vs "Starting Here" vs "Through Here"
The anchor decides which direction information flows, so it is the part people most often leave implicit.
| Anchor | Example state | Final answer location | Typical use |
|---|---|---|---|
| Ending at `(i, j)` | min cost of a path from start to `(i, j)` | `dp[m-1][n-1]` | path counting, min path sum |
| Starting at `(i, j)` | min health needed when entering `(i, j)` to reach the goal | `dp[0][0]` | dungeon-style problems |
| Corner at `(i, j)` | side of the largest all-ones square with bottom-right corner at `(i, j)` | max over all cells | maximal square |
| Path starting at `(i, j)`, any direction | length of the longest increasing path starting at `(i, j)` | max over all cells | longest increasing path |
The anchor you want is not always obvious. In dungeon-style problems, "ending at" seems natural but fails, because the health you need at a cell depends on what comes after it. A later chapter covers that case. For now, the rule is that the anchor should point toward the information the subproblem actually depends on.
A tempting but broken choice is "the best path through (i, j)." That subproblem depends on both the part before the cell and the part after it, so you cannot compute it from neighbors in one direction. Pick one side.
Inclusive or Exclusive: Say Which
For cost problems, decide whether dp[i][j] includes the cost of cell (i, j) itself. Both conventions work, but mixing them produces off-by-one-cell errors that are hard to see. For the grid [[1, 3, 1], [1, 5, 1], [4, 2, 1]]:
| Convention | Row 0 | Row 1 | Row 2 | Answer |
|---|---|---|---|---|
| Inclusive: cost of path to and including `(i, j)` | 1, 4, 5 | 2, 7, 6 | 6, 8, 7 | `dp[2][2]` = 7 |
| Exclusive: cost of path up to but not including `(i, j)` | 0, 1, 4 | 1, 2, 5 | 2, 6, 6 | `dp[2][2] + grid[2][2]` = 7 |
The inclusive form is more common because the answer sits directly in the last cell. Whichever you choose, write it in a comment above the table.
Is the Cell Enough? The Sufficiency Test
A state is sufficient when knowing it tells you everything the rest of the computation needs. Put another way, two different partial paths that reach the same state must be interchangeable for the future. If one of them could still make a move the other cannot, or would be scored differently from here on, the state is missing information.
Apply the test by asking: "If two walkers arrive at (i, j) with the same dp value, could any rule treat them differently from now on?"
- Right/down moves, fixed cell costs: no.
(i, j)is enough. - "You may break through at most k walls": yes. A walker who has used all their breaks differs from one who has not. Add a dimension:
dp[i][j][r]withrbreaks remaining. - "No more than 3 consecutive right moves": yes. Add the current run length and direction.
- Two walkers collecting cherries together: yes. One position cannot describe both walkers. The state needs both positions, which the final chapter reduces to three indices.
Each added dimension multiplies the table size. A grid with k wall breaks costs O(m·n·k) states instead of O(m·n). So add only what the sufficiency test demands.
Common Mistakes When Defining the State
- Storing the path instead of a summary.
dp[i][j]should hold a number or flag. If you need the route, recover it afterward from the filled table, which a later chapter covers. - Defining the global answer instead of a local one. "The minimum cost in the grid" is not a per-cell state. Tie the definition to
(i, j). - Leaving the rules out. "Number of paths to
(i, j)" is ambiguous if diagonal moves or blocked cells exist. Name the moves. - Silent padding offsets, as described in the warning above.
- Choosing "through" as the anchor. It depends on both sides of the cell and cannot be filled in one sweep.
Exercise
A robot moves right or down on an m×n grid of costs and wants the minimum total cost from (0, 0) to (m-1, n-1). Write a complete inclusive state definition, and say where the final answer is stored.
Show answer
dp[i][j] = the minimum total cost, including grid[i][j], over all right/down paths that start at (0, 0) and end at (i, j). The answer is dp[m-1][n-1].
Exercise
Same grid and moves, but the robot may skip paying for at most 2 cells along its path. Why does dp[i][j] fail the sufficiency test, and what state fixes it? How many states are there?
Show answer
Two paths can reach (i, j) with the same cost but different numbers of skips left, and the one with skips remaining can do better later. Use dp[i][j][s] = minimum cost of a path to (i, j) that has used exactly s skips (or has s remaining), with s in {0, 1, 2}. That gives 3·m·n states.
Exercise
Using the brute-force approach from this chapter, what is the value of entry (2, 2) in the state table for a 3×3 grid with right/down moves, and what does that number mean?
Show answer
It is 6, the number of distinct right/down paths from (0, 0) to (2, 2). Each path is an arrangement of 2 right moves and 2 down moves, and C(4, 2) = 6.