Dynamic Programming · Pattern 3 of 12

2D DP: grids and two-index states

The state has two numbers: a cell (r, c) in a grid, or an index plus a budget (dice used and sum, moves and eggs). Each cell is built from neighbours that were filled earlier, and often one row of memory is enough.

3 variations · 13 problems · 5 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Move right or down through a grid and count paths or minimise cost
  • Obstacles or cell values change what a move is worth
  • An index plus a second quantity: a sum, a time limit, a count of items still allowed

The template

2D DP
// Unique Paths II: ways(r, c) = ways from above + ways from the left; obstacles have 0 ways
int uniquePathsWithObstacles(int[][] g) {
    int cols = g[0].length;
    int[] dp = new int[cols];              // dp[c] = ways to reach (current row, c)
    dp[0] = 1;
    for (int[] row : g)
        for (int c = 0; c < cols; c++) {
            if (row[c] == 1) dp[c] = 0;
            else if (c > 0) dp[c] += dp[c - 1];   // old dp[c] is "from above"
        }
    return dp[cols - 1];
}

// Minimum Path Sum, one row of memory
int minPathSum(int[][] g) {
    int rows = g.length, cols = g[0].length;
    int[] dp = new int[cols];
    for (int r = 0; r < rows; r++)
        for (int c = 0; c < cols; c++) {
            if (r == 0 && c == 0) dp[c] = g[0][0];
            else if (r == 0) dp[c] = dp[c - 1] + g[r][c];
            else if (c == 0) dp[c] += g[r][c];
            else dp[c] = Math.min(dp[c], dp[c - 1]) + g[r][c];
        }
    return dp[cols - 1];
}

// Dice Rolls: index (dice used) plus a budget (sum so far)
int numRollsToTarget(int n, int k, int target) {
    final int MOD = 1_000_000_007;
    int[] dp = new int[target + 1];        // dp[s] = ways to reach sum s with the dice so far
    dp[0] = 1;
    for (int d = 1; d <= n; d++) {
        int[] next = new int[target + 1];
        for (int s = 1; s <= target; s++)
            for (int f = 1; f <= k && f <= s; f++)
                next[s] = (next[s] + dp[s - f]) % MOD;
        dp = next;
    }
    return dp[target];
}

The variations

  1. 1Paths through a grid

    A cell is reached from above or from the left. Count paths by adding, minimise cost by taking the smaller. An extra small dimension (robbers you may still neutralise) or a repeated prefix sum (the N-th value after K seconds) is the same grid with one more twist.

  2. 2Fill backwards, or walk twice at once

    When the answer at a cell depends on what comes after it, fill from the end: need(r, c) = max(1, min(need right, need down) - dungeon[r][c]). For two walkers, use the state (step, row of walker 1, row of walker 2) so a cherry is never counted twice.

    Worked example Dungeon Game Hard Read the solution
  3. 3An index plus a budget

    The second dimension is a resource: the sum so far (dice), the time spent (reach the destination in time), events still allowed (events II), or eggs left. For Super Egg Drop, flip the question: with m moves and k eggs, how many floors can you check? f(m, k) = f(m - 1, k - 1) + f(m - 1, k) + 1.

Mistakes to avoid

  • Forgetting that an obstacle in the first row or column blocks every cell after it.
  • Dungeon Game filled from the start: the health you need depends on what is ahead, so fill from the bottom-right corner back.
  • Cherry Pickup done as two separate best paths: the first walk changes the grid. Move both walkers together, one step at a time.
Next: Row by row: the best of the last row →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.