2D grid DP
In grid DP the state is a cell (row, column): the best or the count of ways to reach it, built from the cells you can arrive from. Fill row by row so those cells are ready. Many 'best rectangle' questions fix two rows and reduce the rest to a 1D problem on column sums.
How to recognise it
- Moving through a grid with only some directions allowed.
- Counting paths, or the cheapest or most valuable path.
- The best square or rectangle of a matrix.
Cell by cell
for r in rows:
for c in columns:
dp[r][c] = cell value combined with dp of the cells you arrive from
| Problem | Arrive from |
|---|---|
| unique paths | up, left |
| min cost path | up, left, diagonal |
| falling path, gold mine | the three neighbours in the previous row (or column) |
| triangle | the two below (fill bottom up) |
| cherry pickup II | state is (row, column of robot 1, column of robot 2) |
Rectangles
Fix a top and bottom row (or left and right column); add up each column between them. Now the question is about a 1D array: the best subarray (Kadane), or the longest subarray with sum 0 (prefix sums in a hash map).
Common mistakes
- Overwriting values in one-row tables in the wrong order.
- Forgetting cells blocked by obstacles in the first row and column.
Problems
- Ninja's trainingmediumguide ready
- Unique Pathsmediumguide ready
- Unique Paths IImediumguide ready
- Minimum Falling Path Summediumguide ready
- Trianglemediumguide ready
- Gold Mine Problemmediumguide ready
- Assembly Line SchedulingProblemmediumguide ready
- Maximum size square sub-matrix with all 1smediumguide ready
- Min Cost PathProblemmediumguide ready
- Mobile Numeric Keypad Problemmediumguide ready
- Largest area rectangular sub-matrix with equal number of 1’s and 0’smediumguide ready
- Cherry Pickup IIhardguide ready
- Largest rectangular sub-matrix whose sum is 0hardguide ready
- Maximum sum rectangle in a 2D matrixhardguide ready