Unique Paths II
Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #63
A robot moves only right or down from the top-left corner to the bottom-right corner of a grid. Cells marked 1 are obstacles. Return the number of distinct paths.
Examples
text
[[0,0,0],[0,1,0],[0,0,0]] → 2
[[0,1],[0,0]] → 1Hints
paths(r, c) = paths(r−1, c) + paths(r, c−1), and 0 if the cell is an obstacle.- A single 1-D array is enough: process row by row and update in place.
Approach
Use a 1-D rolling dp of length C, with dp[0] = 1 for the start. For each row, for each column:
- obstacle →
dp[c] = 0 - otherwise →
dp[c] += dp[c−1](for c > 0)
Before the update, dp[c] holds the value from the row above. dp[c−1] already holds this row's left neighbor. If the start or the end is blocked, the answer comes out as 0 automatically.
Complexity
Time: O(R·C). Space: O(C).
Python solution
def uniquePathsWithObstacles(obstacleGrid):
C = len(obstacleGrid[0])
dp = [0] * C
dp[0] = 1
for row in obstacleGrid:
for c in range(C):
if row[c]:
dp[c] = 0
elif c:
dp[c] += dp[c - 1]
return dp[-1]JavaScript solution
function uniquePathsWithObstacles(obstacleGrid) {
const C = obstacleGrid[0].length, dp = new Array(C).fill(0);
dp[0] = 1;
for (const row of obstacleGrid) for (let c = 0; c < C; c++) {
if (row[c]) dp[c] = 0;
else if (c) dp[c] += dp[c - 1];
}
return dp[C - 1];
}