Unique Paths II
Medium
Topics
A robot starts at the top-left cell of grid and wants to reach the bottom-right cell, moving only right or down.
A cell holding 1 is an obstacle and cannot be entered; 0 is free. Return the number of distinct paths. If the start or the finish is an obstacle, the answer is 0.
LeetCode names the argument obstacleGrid; the harness here calls it grid.
Example 1
Input: grid = [[0,0,0],[0,1,0],[0,0,0]] Output: 2 Explanation: The obstacle in the centre leaves one path along the top and right edges and one along the left and bottom edges.
Example 2
Input: grid = [[0,1],[0,0]] Output: 1 Explanation: The only route is down then right.
Example 3
Input: grid = [[1]] Output: 0 Explanation: The start is blocked, so there is no path at all.
Constraints
- 1 <= grid.length, grid[0].length <= 100
- grid[i][j] is 0 or 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
Without obstacles the count is a binomial coefficient, because a path is just a choice of which steps go down. An obstacle destroys that formula, so count by cell instead.
Since the robot only moves right or down, a cell can be reached only from the cell above it or the cell to its left. So the number of paths into a cell is the sum of the paths into those two neighbours — and an obstacle is handled by recording zero paths into it, which propagates naturally without a special case.
That zero is the neat part: there is no need to detect "blocked regions" or prune anything. A cell behind an obstacle receives zero from the blocked side and whatever is legitimately available from the other.
The first row and first column need care. In a plain grid they are all 1, but here a single obstacle in the first row makes every cell after it unreachable along that row, so the row must be filled by carrying the value forward rather than by assigning 1 outright.
Approach
- If the start cell is an obstacle, return
0. - Set the paths into the start cell to
1. - Fill the first row left to right: a free cell inherits the value to its left, and an obstacle gets
0. Do the same down the first column. - For every other cell: an obstacle gets
0, and a free cell gets the sum of the cell above and the cell to its left. - Return the value at the bottom-right cell.
- Only the previous row is ever needed, so one row of storage is enough.
Walkthrough
grid = [[0,0,0],
[0,1,0],
[0,0,0]]
paths into each cell
start is free, so cell (0,0) = 1
first row: carry forward across free cells
1 1 1
first column: carry down
1
1
1
cell (1,1) is an obstacle -> 0
cell (1,2) = above (0,2)=1 + left (1,1)=0 = 1
cell (2,1) = above (1,1)=0 + left (2,0)=1 = 1
cell (2,2) = above (1,2)=1 + left (2,1)=1 = 2
1 1 1
1 0 1
1 1 2
answer 2
why the first row cannot just be all 1s
grid = [[0,1,0]]
(0,0) = 1
(0,1) is an obstacle -> 0
(0,2) inherits 0, not 1
the cell after the obstacle is unreachable.Complexity
- Time — O(rows * cols): each cell is computed once from two neighbours.
- Space — O(cols): one row carried forward; the full table is not needed.
Common Pitfalls
- Filling the first row and column with 1 unconditionally. An obstacle makes everything after it in that line unreachable.
- Forgetting to check the start cell, which can itself be an obstacle.
- Forgetting that the finish can be an obstacle. Summing into it gives
0automatically, so no extra check is needed — but special-casing it wrongly can reintroduce the bug. - Using the binomial formula and then subtracting blocked paths. That works only for very restricted obstacle layouts.
- In the single-row version, writing
row[c] = row[c - 1]instead ofrow[c] += row[c - 1], which drops the contribution from above.
Full Solution — all languages
class Solution:
def uniquePathsWithObstacles(self, grid):
rows, cols = len(grid), len(grid[0])
if grid[0][0] == 1:
return 0
# row[c] = number of paths into the current row's column c
row = [0] * cols
row[0] = 1
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
row[c] = 0 # nothing reaches an obstacle
elif c > 0:
# row[c] is still the cell ABOVE; row[c-1] is the cell LEFT.
row[c] += row[c - 1]
return row[cols - 1]import java.util.*;
class Solution {
public int uniquePathsWithObstacles(int[][] grid) {
int rows = grid.length, cols = grid[0].length;
if (grid[0][0] == 1) return 0;
long[] row = new long[cols];
row[0] = 1;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 1) row[c] = 0;
else if (c > 0) row[c] += row[c - 1];
}
}
return (int) row[cols - 1];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int uniquePathsWithObstacles(vector<vector<int>>& grid) {
int rows = (int)grid.size(), cols = (int)grid[0].size();
if (grid[0][0] == 1) return 0;
vector<long long> row(cols, 0);
row[0] = 1;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 1) row[c] = 0;
else if (c > 0) row[c] += row[c - 1];
}
}
return (int)row[cols - 1];
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var uniquePathsWithObstacles = function(grid) {
const rows = grid.length, cols = grid[0].length;
if (grid[0][0] === 1) return 0;
const row = new Array(cols).fill(0);
row[0] = 1;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === 1) row[c] = 0;
else if (c > 0) row[c] += row[c - 1];
}
}
return row[cols - 1];
};