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.
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
// 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];
} def unique_paths_with_obstacles(g):
cols = len(g[0])
dp = [0] * cols # dp[c] = ways to reach (current row, c)
dp[0] = 1
for row in g:
for c in range(cols):
if row[c] == 1:
dp[c] = 0
elif c > 0:
dp[c] += dp[c - 1] # old dp[c] is "from above"
return dp[-1]
def min_path_sum(g):
rows, cols = len(g), len(g[0])
dp = [0] * cols
for r in range(rows):
for c in range(cols):
if r == 0 and c == 0: dp[c] = g[0][0]
elif r == 0: dp[c] = dp[c - 1] + g[r][c]
elif c == 0: dp[c] += g[r][c]
else: dp[c] = min(dp[c], dp[c - 1]) + g[r][c]
return dp[-1]
def num_rolls_to_target(n, k, target):
MOD = 10**9 + 7
dp = [1] + [0] * target # dp[s] = ways to reach sum s with the dice so far
for _ in range(n):
nxt = [0] * (target + 1)
for s in range(1, target + 1):
for f in range(1, min(k, s) + 1):
nxt[s] = (nxt[s] + dp[s - f]) % MOD
dp = nxt
return dp[target] // Unique Paths II: ways from above + ways from the left; obstacles have 0 ways
int uniquePathsWithObstacles(vector<vector<int>>& g) {
int cols = g[0].size();
vector<long long> dp(cols, 0); // dp[c] = ways to reach (current row, c)
dp[0] = 1;
for (auto& 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(vector<vector<int>>& g) {
int rows = g.size(), cols = g[0].size();
vector<int> dp(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] = 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) {
const int MOD = 1e9 + 7;
vector<int> dp(target + 1, 0); // dp[s] = ways to reach sum s with the dice so far
dp[0] = 1;
for (int d = 1; d <= n; d++) {
vector<int> next(target + 1, 0);
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];
} // Unique Paths II: ways from above + ways from the left; obstacles have 0 ways
function uniquePathsWithObstacles(g) {
const cols = g[0].length, dp = new Array(cols).fill(0);
dp[0] = 1; // dp[c] = ways to reach (current row, c)
for (const row of g)
for (let 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
function minPathSum(g) {
const rows = g.length, cols = g[0].length, dp = new Array(cols).fill(0);
for (let r = 0; r < rows; r++)
for (let 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)
function numRollsToTarget(n, k, target) {
const MOD = 1e9 + 7;
let dp = new Array(target + 1).fill(0);
dp[0] = 1; // dp[s] = ways to reach sum s with the dice so far
for (let d = 1; d <= n; d++) {
const next = new Array(target + 1).fill(0);
for (let s = 1; s <= target; s++)
for (let f = 1; f <= k && f <= s; f++) next[s] = (next[s] + dp[s - f]) % MOD;
dp = next;
}
return dp[target];
} The variations
-
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.
Now you solve -
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.Now you solve -
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
mmoves andkeggs, 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.
Lesson done
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.