Grid DP problems place you on a 2D board where you may only move in restricted directions (usually right and down) and ask you to count paths, minimize cost or maximize reward. Because moves only go one way, every cell depends on cells above and to the left, so a single row-by-row sweep solves the problem. Grids are the friendliest place to practice 2D DP, and they hide a few traps worth knowing: obstacles on the border, problems that must be solved backward, and closed-form shortcuts.
Think of it like
A courier in a one-way city
Imagine a city of perfect square blocks where every street is one-way: you may only drive east or south. To know the cheapest route to any intersection, you only need the cheapest routes to the intersection just north of it and the one just west of it. Fill in the city map block by block from the northwest corner and the answer for the far corner falls out at the end.
The grid pattern
Let dp[r][c] be the answer for the subproblem that ends at cell (r, c): the number of ways to reach it, or the cheapest cost to reach it. If the only moves are right and down, the last move into (r, c) came from (r-1, c) or (r, c-1). Those are earlier in row-major order, so a plain double loop computes everything in dependency order.
Unique paths
A robot starts in the top-left corner of an m × n grid and moves only right or down. How many distinct paths reach the bottom-right corner?
- 1
State
ways[r][c]= the number of distinct right/down paths from(0, 0)to(r, c). - 2
Last move
The final step came from above or from the left; the two sets of paths are disjoint, so add them.
- 3
Base cases
Every cell of the first row and first column has exactly one path (a straight line), so they are 1.
- 4
Order and answer
Row by row, left to right. The answer is
ways[m-1][n-1].
| c=0 | 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|---|
| r=0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| r=1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| r=2 | 1 | 3 | 6 | 10 | 15 | 21 | 28 |
The combinatorial closed form
Every path makes exactly m − 1 down moves and n − 1 right moves, in some order. A path is fully determined by choosing which of the m + n − 2 moves are downs. The table above is Pascal's triangle tilted on its side.
Unique paths with obstacles
Now some cells are blocked. A blocked cell has 0 paths through it, and the recurrence is otherwise unchanged. The trap is the border: you cannot blindly set the first row and column to 1, because everything after an obstacle in the first row is unreachable.
| c=0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| r=0 | 1 | 1 | X | 0 |
| r=1 | 1 | X | 0 | 0 |
| r=2 | 1 | 1 | 1 | 1 |
The cleanest implementation avoids special-casing the border altogether: initialize ways[0][0] = 1 (if it is free) and treat out-of-bounds neighbors as 0. Then the same line of code handles every cell, obstacles included. Also check the start and end cells: if either is blocked, the answer is 0.
Minimum path sum
Each cell holds a nonnegative cost; find the right/down path from top-left to bottom-right with the smallest total.
- 1
State
best[r][c]= the minimum total cost of a path from(0, 0)to(r, c), including both endpoints. - 2
Last move
Arrive from above or from the left, whichever is cheaper, then pay this cell's cost.
- 3
Base cases
best[0][0] = grid[0][0]; the first row and column are running sums (only one way to get there). - 4
Order and answer
Row by row; the answer is
best[m-1][n-1].
| grid | c=0 | 1 | 2 | best | c=0 | 1 | 2 | |
|---|---|---|---|---|---|---|---|---|
| r=0 | 1 | 3 | 1 | r=0 | 1 | 4 | 5 | |
| r=1 | 1 | 5 | 1 | r=1 | 2 | 7 | 6 | |
| r=2 | 4 | 2 | 1 | r=2 | 6 | 8 | 7 |
Dungeon game: when the DP must run backward
A knight starts at the top-left of a dungeon and must reach the princess at the bottom-right, moving right or down. Each cell adds to or subtracts from his health (demons are negative, potions positive), and if his health ever drops to 0 he dies. What is the minimum initial health that guarantees he survives?
Why the forward DP fails
Going forward, a partial path is described by two numbers: the health required so far and the health remaining now. Neither one alone is enough, and the two can disagree. Consider this dungeon:
| c=0 | 1 | 2 | |
|---|---|---|---|
| r=0 | +1 | −3 | +3 |
| r=1 | 0 | −2 | 0 |
| r=2 | −3 | −3 | −3 |
Path A to cell (1, 2): down, right, right
- Needs only 2 starting health so far
- Arrives with just 1 health left
- The final −3 kills it: total requirement becomes 5
- A forward DP that keeps the path with the smallest requirement picks this one
Path B to cell (1, 2): right, right, down
- Needs 3 starting health so far
- Arrives with 4 health thanks to the +3 potion
- Survives the final −3 with 1 health: requirement stays 3
- The true optimum, discarded by the forward greedy choice
The future (the −3 waiting at the end) decides which history was better, so the forward state is not a single comparable number. Reverse the direction and the problem has a clean one-number state: how much health do I need when entering this cell to survive everything that comes after it?
- 1
State
need[r][c]= the minimum health the knight must have when entering(r, c)to reach the princess alive. - 2
Next move
From
(r, c)he goes right or down; he picks the one that needs less,min(need[r+1][c], need[r][c+1]). He must arrive with that much after this cell's effect, so he needsthat − dungeon[r][c]before it. - 3
Clamp
Health must always be at least 1, so take
max(1, …). A big potion cannot make the requirement drop below 1. - 4
Base cases and order
Pretend the cells just below and just right of the princess need 1 (all other out-of-bounds cells are ∞). Fill from bottom-right to top-left; the answer is
need[0][0].
| dungeon | c=0 | 1 | 2 | need | c=0 | 1 | 2 | |
|---|---|---|---|---|---|---|---|---|
| r=0 | −2 | −3 | 3 | r=0 | 7 | 5 | 2 | |
| r=1 | −5 | −10 | 1 | r=1 | 6 | 11 | 5 | |
| r=2 | 10 | 30 | −5 | r=2 | 1 | 1 | 6 |
Triangle
Find the minimum path sum from the top of a triangle to the bottom, moving at each step to one of the two adjacent numbers in the row below (index c or c + 1). Solving it bottom-up removes every edge case: start with the last row as the DP array and fold each row into the one above.
| Row (triangle values) | dp after processing this row |
|---|---|
| 4 1 8 3 (bottom) | [4, 1, 8, 3] |
| 6 5 7 | [6+1, 5+1, 7+3] = [7, 6, 10] |
| 3 4 | [3+6, 4+6] = [9, 10] |
| 2 (top) | [2+9] = [11] |
Maximal square
In a binary matrix, find the area of the largest square containing only 1s. The key is choosing the state: let side[r][c] be the side length of the largest all-ones square whose bottom-right corner is (r, c).
Why the minimum of three? A square of side k ending at (r, c) needs squares of side k − 1 ending at the cell above, the cell to the left and the cell diagonally up-left; together they cover the whole square except the corner itself. The weakest of the three neighbors limits how far the square can grow.
| matrix | c=0 | 1 | 2 | 3 | 4 | side | c=0 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| r=0 | 1 | 0 | 1 | 0 | 0 | r=0 | 1 | 0 | 1 | 0 | 0 | |
| r=1 | 1 | 0 | 1 | 1 | 1 | r=1 | 1 | 0 | 1 | 1 | 1 | |
| r=2 | 1 | 1 | 1 | 1 | 1 | r=2 | 1 | 1 | 1 | 2 | 2 | |
| r=3 | 1 | 0 | 0 | 1 | 0 | r=3 | 1 | 0 | 0 | 1 | 0 |
def maximal_square(matrix: list[list[str]]) -> int:
if not matrix:
return 0
n = len(matrix[0])
side = [0] * (n + 1) # side[c + 1] holds the value for column c; side[0] is a 0 sentinel
best = 0
for row in matrix:
diag = 0 # side[r-1][c-1] for c = 0
for c in range(n):
up = side[c + 1]
if row[c] == "1":
side[c + 1] = 1 + min(up, side[c], diag)
best = max(best, side[c + 1])
else:
side[c + 1] = 0
diag = up
return best * bestCherry pickup: two walkers at once
In Cherry Pickup you walk from the top-left to the bottom-right (right/down) and back (left/up), collecting cherries, which disappear once picked. Running the best single path twice is wrong: the first greedy trip can ruin the second. Instead, model the return trip as a second walker going forward at the same time.
- After
tsteps both walkers satisfyr + c = t, so the state(t, r1, r2)determines both positions (c1 = t − r1,c2 = t − r2). - Each step, both walkers move right or down: 4 combinations of previous states.
- If both stand on the same cell, count its cherries once. This is the reason to move them simultaneously.
- There are O(n) values of
tand O(n²) pairs of rows, so O(n³) time; rolling overtgives O(n²) space. - Cherry Pickup II starts two robots in the top corners moving down one row per step; the state is
(row, c1, c2)with 9 transitions.
Saving space on grids
Each row only reads the row above, so a single array of length n is enough. Before you update dp[c] in row r, it still holds dp[r-1][c] (the value from above), and dp[c-1] already holds the current row's value (the value from the left). That is exactly what the recurrence needs.
def unique_paths(m: int, n: int) -> int:
row = [1] * n # first row: one path to each cell
for _ in range(1, m):
for c in range(1, n):
row[c] += row[c - 1] # row[c] (old) = from above, row[c-1] (new) = from the left
return row[-1]- Index the array by the shorter dimension to get O(min(m, n)) space.
- If a recurrence also reads the up-left diagonal (maximal square, edit distance), save the old value in a
diagvariable before overwriting. - For backward problems (dungeon, triangle), sweep from the last row upward and from right to left.
- Keep the full table if you must reconstruct the path itself.
Complexity
| Problem | Time | Space | Notes |
|---|---|---|---|
| Unique paths (DP) | O(m·n) | O(min(m, n)) | One rolling row |
| Unique paths (closed form) | O(min(m, n)) | O(1) | Binomial coefficient C(m+n−2, m−1) |
| Unique paths with obstacles | O(m·n) | O(n) | Blocked cells are 0 |
| Minimum path sum | O(m·n) | O(n) | O(m·n) to reconstruct the path |
| Dungeon game | O(m·n) | O(n) | Filled from the bottom-right |
| Triangle | O(n²) | O(n) | n rows, n(n+1)/2 cells |
| Maximal square | O(m·n) | O(n) | Saved diagonal variable |
| Cherry pickup | O(n³) | O(n²) | Two simultaneous walkers |
Every grid DP here does O(1) work per cell (except cherry pickup's O(1) per pair of cells), so time equals the number of states.
Implementation
A one-row DP that handles blocked cells (1 = obstacle) without border special cases, plus the binomial formula for empty grids.
def unique_paths_with_obstacles(grid: list[list[int]]) -> int:
n = len(grid[0])
row = [0] * n
row[0] = 1 # one way to stand on the start (if free)
for r in range(len(grid)):
for c in range(n):
if grid[r][c] == 1:
row[c] = 0 # blocked: no path passes through
elif c > 0:
row[c] += row[c - 1] # from above (old row[c]) + from the left
return row[-1]
def unique_paths(m: int, n: int) -> int:
# C(m + n - 2, k) with k = min(m, n) - 1, built incrementally (stays an integer)
total, k = m + n - 2, min(m, n) - 1
result = 1
for i in range(1, k + 1):
result = result * (total - k + i) // i
return result
print(unique_paths(3, 7)) # 28
print(unique_paths_with_obstacles([[0, 0, 0], [0, 1, 0], [0, 0, 0]])) # 2Key takeaways
- With right/down moves,
dp[r][c]depends only on the cell above and the cell to the left, so a row-major sweep is a valid order. - Unique paths has the closed form C(m+n−2, m−1); obstacles, weights or blocked borders require the DP.
- Initialize borders carefully: an obstacle in the first row or column blocks everything after it.
- If the best choice depends on the future (minimum health in dungeon game), define the state as "needed from here to the end" and fill backward.
- Pick states anchored at a corner (
side[r][c]for maximal square) and roll the table to one row, saving the diagonal when needed.
Common pitfalls
- Setting the whole first row and column to 1 in unique paths with obstacles.
- Trying dungeon game forward with a single number per cell; it silently gives wrong answers.
- Forgetting the
max(1, …)clamp in dungeon game, which lets potions reduce the requirement below 1. - Using grid DP when moves can go in all four directions (cycles); that needs BFS or Dijkstra.
- Overwriting the up-left diagonal value in a one-row implementation before reading it.
Interview tips
- Ask which moves are allowed and whether values can be negative before choosing an approach.
- Mention the binomial closed form for unique paths, then explain why it breaks with obstacles.
- For dungeon game, present the forward counterexample briefly to justify the backward DP.
- Offer the O(n) space version and say what it costs (no path reconstruction).
Real-world applications
- Robot motion planning on occupancy grids with restricted movement.
- Image processing: seam carving finds minimum-energy paths with a grid DP.
- Finding the largest empty square or rectangle in layout, map and chip-design grids.
- Lattice path counting in combinatorics and probability (random walks, ballot problems).
Practice problems
Test yourself
How many right/down paths cross a 3 × 3 grid from the top-left to the bottom-right cell?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.