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. 1.Unique Paths
    medium
  2. 2.Unique Paths II
    medium
  3. 3.Minimum Path Sum
    medium
  4. 4.Triangle
    medium
  5. 5.Minimum Falling Path Sum
    medium
  6. 6.Maximal Square
    medium
  7. 7.Dungeon Game
    hard
  8. 8.Cherry Pickup
    hard
  9. 9.Cherry Pickup II
    hard
  10. 10.Count Square Submatrices with All Ones
    medium
  11. 11.Minimum Path Cost in a Grid
    medium
  12. 12.Out of Boundary Paths
    medium
  13. 13.Number of Paths With Maximum Score
    hard
  14. 14.Paths in Matrix Whose Sum Is Divisible by K
    medium
  15. 15.Maximum Non-Negative Product in a Matrix
    medium
  16. 16.Minimum Number of Visited Cells in a Grid — advanced
    hard
  17. 17.Longest Increasing Path in a Matrix — DFS + Memoization
    hard
  18. 18.Unique Paths III — compare with Backtracking
    hard

Also Important

7 advanced Grid DP variations worth practicing.

  1. 19.Falling Path Variants
    medium
  2. 20.Grid DP with Obstacles
    medium
  3. 21.Grid DP with Extra State
    medium
  4. 22.Two-Agent Grid DP
    hard
  5. 23.Maximum Path Sum in Matrix
    medium
  6. 24.Minimum Health / Resource DP
    hard
  7. 25.Grid DP Space Optimization
    medium

How to Think

First define: dp[r][c] means __________, then identify reachable incoming neighbors.

  1. Movement only from fixed directions?Grid DP
  2. Need count paths?dp[r][c] = top + left
  3. Need minimum cost?dp[r][c] = cell + min(top, left)
  4. Need maximum score?dp[r][c] = cell + max(top, left)
  5. 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.

Visual Memory Rule
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