Pattern #69
Grid DP
Propagate path counts, minimum costs, and maximum scores across 2D grids. Solve directional move transitions, reverse health DP, and extra state dimensions.
Must Solve
18 core questions — solve these first.
- 1.Unique PathsGrid DP path counting: dp[r][c] = dp[r-1][c] + dp[r][c-1]medium
- 2.Unique Paths IIGrid DP with obstacles: if obstacle dp[r][c] = 0, else top + leftmedium
- 3.Minimum Path SumGrid DP min cost: dp[r][c] = grid[r][c] + min(dp[r-1][c], dp[r][c-1])medium
- 4.TriangleBottom-up accumulation: dp[r][c] += min(dp[r+1][c], dp[r+1][c+1])medium
- 5.Minimum Falling Path SumGrid DP: dp[r][c] = matrix[r][c] + min(upper-left, up, upper-right)medium
- 6.Maximal SquareGrid DP square growth: dp[r][c] = 1 + min(top, left, diagonal) for 1smedium
- 7.Dungeon GameReverse Grid DP: compute min health needed from destination (E) to start (S)hard
- 8.Cherry Pickup3D/2D Grid DP with 2 simultaneous paths: dp[r1][c1][r2]hard
- 9.Cherry Pickup IITwo-agent Grid DP: dp[row][col1][col2] evaluating 9 next column pairshard
- 10.Count Square Submatrices with All OnesGrid DP: dp[r][c] = min(top, left, diagonal) + 1; answer = sum(dp)medium
- 11.Minimum Path Cost in a GridGrid DP + edge transition costs between adjacent rowsmedium
- 12.Out of Boundary Paths3D Grid DP: dp[r][c][moves] counting paths exiting grid boundsmedium
- 13.Number of Paths With Maximum ScoreGrid DP tracking pairs: (maxScore, countWays)hard
- 14.Paths in Matrix Whose Sum Is Divisible by K3D Grid DP state: dp[r][c][rem] where rem = pathSum % Kmedium
- 15.Maximum Non-Negative Product in a MatrixGrid DP tracking maxProduct and minProduct due to negative sign flipsmedium
- 16.Minimum Number of Visited Cells in a Grid — advancedGrid DP + monotonic stack or segment tree range minimumshard
- 17.Longest Increasing Path in a Matrix — DFS + MemoizationDFS + Memoization for 4-directional strictly increasing grid pathshard
- 18.Unique Paths III — compare with BacktrackingGrid Backtracking / Bitmask DP visiting all empty cells exactly oncehard
Also Important
7 advanced Grid DP variations worth practicing.
- 19.Falling Path VariantsMulti-direction upper neighbor grid path transitionsmedium
- 20.Grid DP with ObstaclesZeroing unreachable cell path counts behind obstaclesmedium
- 21.Grid DP with Extra State3D DP state expansion dp[r][c][k] for remaining resource kmedium
- 22.Two-Agent Grid DPSimultaneous 2-robot traversal state dp[row][c1][c2]hard
- 23.Maximum Path Sum in MatrixDirectional grid score maximization DPmedium
- 24.Minimum Health / Resource DPReverse destination-to-source health survival DPhard
- 25.Grid DP Space OptimizationReducing O(R*C) grid DP table to 1D row array O(C)medium
How to Think
First define: dp[r][c] means __________, then identify reachable incoming neighbors.
- Movement only from fixed directions?Grid DP
- Need count paths?dp[r][c] = top + left
- Need minimum cost?dp[r][c] = cell + min(top, left)
- Need maximum score?dp[r][c] = cell + max(top, left)
- Dependencies depend on future requirements?Reverse DP (End → Start)
Go Quick Reference — Grid DP
Compilable Go code demonstrating Minimum Path Sum 2D matrix DP and Space-Optimized Unique Paths O(C) 1D row array.
package main
import "fmt"
// Minimum Path Sum 2D Matrix DP: O(R * C) time and space
func minPathSum(grid [][]int) int {
if len(grid) == 0 || len(grid[0]) == 0 {
return 0
}
r, c := len(grid), len(grid[0])
dp := make([][]int, r)
for i := range dp {
dp[i] = make([]int, c)
}
// Base Case initialization
dp[0][0] = grid[0][0]
for j := 1; j < c; j++ { dp[0][j] = dp[0][j-1] + grid[0][j] }
for i := 1; i < r; i++ { dp[i][0] = dp[i-1][0] + grid[i][0] }
// Fill Matrix
for i := 1; i < r; i++ {
for j := 1; j < c; j++ {
minPrev := dp[i-1][j] // top
if dp[i][j-1] < minPrev {
minPrev = dp[i][j-1] // left
}
dp[i][j] = grid[i][j] + minPrev
}
}
return dp[r-1][c-1]
}
// Unique Paths Space-Optimized: O(C) space
func uniquePaths(m int, n int) int {
dp := make([]int, n)
for j := 0; j < n; j++ { dp[j] = 1 } // First row
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
dp[j] = dp[j] + dp[j-1] // dp[j] (top) + dp[j-1] (left)
}
}
return dp[n-1]
}
func main() {
grid := [][]int{{1, 3, 1}, {1, 5, 1}, {4, 2, 1}}
fmt.Println("Min Path Sum:", minPathSum(grid)) // Output: 7
fmt.Println("Unique Paths:", uniquePaths(3, 7)) // Output: 28
}👉 Grid DP: O(R × C) time and O(R × C) or O(C) compressed space.
Core Grid DP Patterns & Operations
4 Main Grid DP Goal Types
1. Path Counting: dp[r][c] = top + left (Unique Paths).
2. Min Cost: dp[r][c] = cell + min(top, left) (Min Path Sum).
3. Max Score: dp[r][c] = cell + max(top, left) (Cherry Pickup).
4. Square Size: dp[r][c] = 1 + min(top, left, diag) (Maximal Square).
Obstacles & Boundaries
• Obstacle Cell: Set dp[r][c] = 0. Path flow breaks completely behind it.
• Border Bounds: Ensure r-1 >= 0 and c-1 >= 0 or use boundary padding to avoid panics.
Define dp[r][c] Cell Meaning → Allowed Movement → Combine Incoming Neighbors
Obstacle Cell → Set dp[r][c] = 0 to break path flow
Dungeon Game → Reverse DP (fill destination-to-start health requirements)
Falling Path → Final answer is min(last row), NOT always bottom-right cell
Space Compression → Keep 1D row array dp[c] to reduce O(R*C) to O(C)Grid DP Variants & Algorithm Distinctions
Reverse & Extra-State Grid DP
• Reverse DP (Dungeon Game): Calculate from destination to start when future health requirements dictate current decisions.
• Extra State DP (Remainder / K Moves): Expand to 3D state dp[r][c][rem] when path sum remainder or resource budget matters.
Grid DP vs BFS / Dijkstra / Backtracking
• Grid DP: Directional moves (right/down) + path counting/costs.
• Grid BFS: Unweighted 4-directional shortest path moves.
• Grid Dijkstra: Weighted 4-directional paths.
• Backtracking: Must visit every cell exactly once (Unique Paths III).
1D Row Space Optimization
Since row r reads only row r-1:
Maintain a single 1D array dp[c].
• Value at dp[c] before update represents Top.
• Value at dp[c-1] after update represents Left.
Reduces space from O(R × C) to O(C) (or O(min(R, C))).
Common Interview Mistakes
- • Assuming every grid matrix problem is Grid DP (could be BFS, DFS, Dijkstra, or Backtracking).
- • Failing to set blocked obstacle cells to 0, allowing paths to pass through walls.
- • Using 0 for minimum path cost initializations instead of infinity (INF).
- • Automatically returning dp[R-1][C-1] when the answer is min(last row) in Falling Path DP.
- • Filling the matrix in the wrong direction when dependencies require reverse end-to-start fill (e.g. Dungeon Game).
- • Forgetting extra state dimensions when path remainder or obstacle removals affect future choices.
- • Overwriting in-place grid cells prematurely during space optimization when original costs are still needed.
- • Failing to handle matrix boundary guards (r-1 < 0 or c-1 < 0), causing index out-of-bounds panics.
- • Allocating a massive R x C matrix without checking memory constraints (Memory Limit Exceeded).
Interview Rules
Fixed directional movement + grid? → Grid DP
Rule 1 → Define dp[r][c] cell meaning explicitly
Rule 2 → Set base starting cells & obstacle zeroes
Rule 3 → Identify allowed incoming movements (top, left, diagonal)
Rule 4 → Combine: + for paths, min for costs, max for scores
Rule 5 → Reverse requirements (Dungeon Game) = Fill End to Start
Rule 6 → Compress space to 1D row array O(C)
Time Complexity → Cells × Transitions (O(R * C) or O(R * C * K))
Space Complexity → O(R * C) Matrix or O(C) Compressed Row💡 Golden Rule: For every cell, define exactly what answer it stores, then combine the already-solved cells that are allowed to lead into it.
Production Thinking
Image & Matrix Cost Propagation → Grid DP propagates directional transformation costs or seam carving thresholds efficiently.
Layout Routing & Grid Optimization → directional robot routing or pipeline layout planning evaluates optimal cell costs via Grid DP.
Precomputed Movement Maps → directional grid DP matrices precompute minimum traversal costs for instant O(1) query lookups.
Production warning → matrix memory scales with R × C; allocate compressed 1D rows to prevent Out-Of-Memory crashes on huge grids.
Remember This
Grid DP State: dp[r][c]
Goal Operations: Path count (+), Min cost (min), Max score (max), Square size (min+1)
Obstacles: Set dp[r][c] = 0
Dungeon Game: Reverse fill (Destination → Start)
Falling Path DP: Return min(last row)
Space Optimization: Reduce O(R*C) matrix to O(C) row array