DP on grids: the state is the cell
1 A rider on one-way streets
A delivery rider starts at a shop on the top-left crossing of a small town and rides to a customer on the bottom-right crossing. The streets are one-way, so she can only ride right or down. The grid shows how many minutes she waits at each crossing's traffic light, the first and last included.
Two questions come up: how many routes are there, and which one waits the fewest minutes? These are Unique Paths and Minimum Path Sum.
The quick idea is to take the cheaper of the next two crossings every time. From the 2, she rides down to 3 and 5, and then along the bottom row through the 9:
The best route takes 15. A cheap step now can lead into a slow street later, so we have to compare routes. Here there are only 10, but a 20 × 20 grid has about 3.5 × 10¹⁰. Trying each one gets TLE. The DP from the last lessons fixes this, with one change: the state is now a cell.
2 Counting routes: look at the last move
We start with one crossing, (1, 2): row 1 and column 2, counted from 0. Three routes reach it, and each one ends with a last move:
One route comes down from (0, 2), the crossing above. Two come right from (1, 1), the crossing on the left. Every route is in exactly one of these groups. So the count for a crossing is the count above plus the count on the left. The state is ways(r, c), the number of routes from the shop to (r, c).
The formula cannot work on the edges. The only way to a crossing on the top row is to ride right all the way, so it has 1 route. The left column is the same with downs. These are the base cases.
A road block fits the same rule. A blocked crossing has 0 routes, and the cells after it add that 0 like any other count:
3 The cheapest route: same cell, min instead of plus
The cheapest route uses the same cell and the same last move. Now cost(r, c) is the fewest minutes to reach (r, c), its own wait included. She waits at (r, c) whichever way she comes, so she should arrive by the cheaper neighbour:
A short proof shows why. The best route through the cell above must reach that cell as cheaply as possible, because a cheaper way there would make a cheaper route to (r, c).
The base cases change too. Each edge crossing has one route, so its cost is a running sum: 2, 8, 16, 18 along the top, and 2, 5, 10 down the left.
| Part | Counting routes | Cheapest route |
|---|---|---|
| State | ways(r, c) | cost(r, c) |
| Transition | above + left | grid[r][c] + min(above, left) |
| Base cases | 1 on the top row and left column | running sums on the top row and left column |
| Answer | the bottom-right cell | the bottom-right cell |
In the steps, the blue cell is being filled and the orange cells are the two it reads:
| (r, c) | grid[r][c] | above | left | cost(r, c) |
|---|---|---|---|---|
| (1, 1) | 6 | 8 | 5 | 11 |
| (1, 2) | 1 | 16 | 11 | 12 |
| (1, 3) | 6 | 18 | 12 | 18 |
| (2, 1) | 9 | 11 | 10 | 19 |
| (2, 2) | 1 | 12 | 19 | 13 |
| (2, 3) | 2 | 18 | 13 | 15 |
The bottom-right cell holds 15. At (2, 2), the cheaper neighbour is above, 12 against 19. The best route stays on row 1 past the 9 and drops to the bottom row at column 2.
4 The fill order, the code and the cost
We fill row by row, each row from left to right. When the loop reaches (r, c), the cell above sits in a finished row, and the cell on the left came earlier in this row. So both inputs are ready before any cell needs them. A memo keyed by (r, c), as in the first DP lesson, also works: cost(2, 3) asks for cost(1, 3) and cost(2, 2), and the recursion finds the order by itself.
C++
Each row is its own vector. vector<int>(cols, 0) is copied once per row, so writing into one row leaves the others alone.
new int[rows][cols] starts full of 0s, and every row is a separate array.
Build each row in the loop. [[0] * cols] * rows puts the same list in every row, so writing one cell writes the whole column.
Array.from builds separate rows. new Array(rows).fill(new Array(cols)) puts one shared array in every row, so writing one cell writes the whole column.
Make each row. make([][]int, rows) gives rows that are all nil. Each one needs its own make([]int, cols).
vec![vec![0; cols]; rows] clones the inner row, so every row is separate. The type of the 0 comes from grid, so cost holds i32.
A rectangular array. new int[rows, cols] holds the whole table in one block, and a cell is cost[r, c]. It starts full of 0s.
Every tab returns 15 on the rider's grid, 5 on [[5]], and 6 on both [[1, 2, 3]] and [[1], [2], [3]]. On a single row or column, the edge loops do all the work.
Each of the R × C cells takes one min, O(1). So the time is O(R·C): about 10⁵ steps for 10⁵ cells. The table takes O(R·C) space.
5 One row is enough
A cell reads only the row above and its own row, so older rows are never read again. The space optimisation lesson kept two values for the robber. Here we keep one row, ways, and write each new row over the old one. When the loop reaches column c:
ways[c]is not updated yet. It still holds the old row's value, the cell above.ways[c - 1]was just updated. It holds the new row's value, the cell on the left.
So the transition is one line, ways[c] = ways[c] + ways[c - 1]. On the counting grid, starting from the top row of 1s:
Slot 0 stays 1, as the left column does. The cheapest route works the same way, with the edges as special cases:
cost = array of C slots
for r from 0 to R - 1
for c from 0 to C - 1
if r == 0 and c == 0
cost[c] = grid[0][0]
else if r == 0
cost[c] = cost[c - 1] + grid[r][c]
else if c == 0
cost[c] = cost[c] + grid[r][c]
else
cost[c] = grid[r][c] + min(cost[c], cost[c - 1])
return cost[C - 1]
Time stays O(R·C), and space drops to O(C). The next lesson, on knapsack, keeps one row too, but there the row must be filled from right to left.
6 Rebuilding the route
The table holds costs, not the route. To get the route, we walk back from the bottom-right cell. At each cell, the route came from the neighbour with the smaller cost, above or on the left. On an edge, only one neighbour exists.
From 15, the walk goes left (13 beats 18), up (12 beats 19), left (11 beats 16), left (5 beats 8), and up the left column to the shop. Read forwards, the route is down, right, right, down, right. The walk needs the full table: with one row, the earlier rows are gone.
7 Mistakes and edge cases
- A road block on an edge. Filling the top row with 1s ignores a block there. With (0, 2) blocked, nothing can reach (0, 3), but it gets 1, and the count comes out 8 instead of 7. Once an edge cell is blocked, every edge cell after it has 0 routes.
- Reading row −1. Running the transition on row 0 reads
cost[r - 1][c]outside the table: a Runtime Error, or in Python a quiet read of the last row. Fill the edges first, as the code does. - One row filled right to left. Then
ways[c - 1]still holds the old row's value, the cell above and to the left. On the 3 × 4 grid, the count comes out 4 instead of 10. - Overflow in the count. The routes number C(R + C − 2, R − 1), one for each choice of which moves are downs. An 18 × 18 grid has about 2.3 × 10⁹, past a 32-bit
int, and a 100 × 100 grid about 2.3 × 10⁵⁸, past 64 bits. So problems ask for the count modulo 10⁹ + 7, taken after every addition.
8 When to use it, and other grids
The sign is a grid where the moves never come back, such as right and down, and a question about the number of paths or the best total along one. The state is the cell, and the transition reads the cells a move could have come from. Other grids bend the idea:
- Triangle. A step goes down to one of two cells. Filling from the bottom row up leaves the answer at the top.
- Minimum Falling Path Sum. A step goes down, down-left or down-right, so each cell reads three cells in the row above.
- Count Square Submatrices with All Ones. Each cell reads the cells above, on the left and above-left.
- Cherry Pickup II. Two walkers go down together, so the state grows to (r, c1, c2), the row and both columns.
- Dungeon Game. What a cell needs depends on the cells after it, so the table fills from the end back.
- Longest Increasing Path in a Matrix. Moves go in all four directions, so no row order works, and the memo finds the order.
Practice it
- Unique PathsMedium
- Unique Paths IIMedium
- Longest Increasing Path in a MatrixHard
- Minimum Path SumMedium
- TriangleMedium
- Minimum Falling Path SumMedium
- Count Square Submatrices with All OnesMedium
- Cherry Pickup IIHard
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.