Unique Paths II

Medium

Topics
ArrayDynamic ProgrammingMatrix

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

1111✕1112
paths that reach this cellobstacle
On this 3 by 3 board the answer is 2, shown in the bottom-right cell. Each number is how many ways the robot can reach that cell moving only right or down, so a cell is the sum of the one above it and the one to its left. An obstacle holds zero, and that zero spreads: a cell behind one receives nothing from that side, which is how blocked regions take care of themselves.
Cells show path counts rather than the input values; an obstacle is drawn as a cross.
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

1✕11
paths that reach this cellobstacle
Input:  grid = [[0,1],[0,0]]
Output: 1
Explanation: The only route is down then right.

Example 3

✕
obstacle
The starting cell is itself blocked here, which makes every count zero before the board even matters.
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

  1. If the start cell is an obstacle, return 0.
  2. Set the paths into the start cell to 1.
  3. 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.
  4. 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.
  5. Return the value at the bottom-right cell.
  6. 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 0 automatically, 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 of row[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]
SensAI
Beta
Tap the mic to stop voice mode