LeetCode #63 Medium

Unique Paths II

Unique Paths II is LeetCode 63 (Medium). You get an m × n grid obstacleGrid where 1 marks an obstacle and 0 an open cell. A robot starts at the top-left cell, moves only right or down, and may never step on an obstacle. Return the number of routes to the bottom-right cell.

  • Either corner can itself be an obstacle, and then the answer is 0.
  • m and n are at most 100, and the answer is at most 2 × 10⁹.
Constraints
  • m == obstacleGrid.length
  • n == obstacleGrid[i].length
  • 1 <= m, n <= 100
  • obstacleGrid[i][j] is 0 or 1
  • The answer is at most 2 × 10⁹
dynamic-programmingmatrixgrid
Open on LeetCode ↗
02

Intuition

Without rocks, routes into a cell = routes into the cell above + routes into the cell on its left. A rock changes just one thing: no route can stand on it, so its count is 0. That 0 then flows on by itself. The cell to its right gets nothing from the left, and the cell below gets nothing from above.

The tricky part is the edges. In an open grid the whole top row and left column are 1. Here a rock in the top row cuts off every cell after it in that row, since they can only be reached through it. A single array handles that without special cases if it starts as [1, 0, 0, …] and each cell is processed in order: the 0 from the rock is what the next cell adds.

How to spot this pattern

Counting monotone routes on a grid where some cells are forbidden is grid DP with a reset: forbidden cells contribute 0, everything else adds what flows in from above and from the left.

03

Approach

Try it first

Before reading on, take the 3 × 3 grid with one rock in the middle and count routes by hand. Then ask: how many routes reach a rock, and what does that do to the cells right of it and below it?

1

One array of route counts

Make ways of length n, all 0, then set ways[0] = 1. That 1 is the single route that starts at the top-left cell; the zeros mean no route has reached the rest of the top row yet.

2

Walk every cell row by row

For each row, go left to right. At column j, ways[j] still holds the count for the cell above, and ways[j - 1] was just updated for the cell on the left.

3

A rock sets the count to 0

If the cell holds 1, set ways[j] = 0. It wipes out the count carried down from above, so nothing passes through, and it hands a 0 to the cell on its right.

4

An open cell adds its left neighbour

Otherwise, for j > 0, do ways[j] += ways[j - 1]. Column 0 adds nothing, since it has no left neighbour, and simply keeps the count from above, which turns 0 for good once a rock appears in that column.

5

Return the last entry

After the final row, ways[n - 1] is the count for the bottom-right cell. If that cell is a rock, the last update already set it to 0.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
▶3 n = len(obstacleGrid[0])
▶4 ways = [0] * n
▶5 ways[0] = 1
▶6 for row in obstacleGrid:
▶7 for j in range(n):
▶8 if row[j] == 1:
▶9 ways[j] = 0
▶10 elif j > 0:
▶11 ways[j] += ways[j - 1]
▶12 return ways[n - 1]
gridrockways array1col 10col 20col 3this cell+=start: 1 route begins at the top-left
ways1 0 0
The array holds one route count per column. It starts as 1 in column 1 and 0 elsewhere: the robot's single route begins in the corner, and no route has reached the other cells yet. Nothing else is assumed, so a rock anywhere, even on the start, is handled by the same loop.
grid1rockways array1col 10col 20col 3this cell1→1no left cellleft edge: keeps 1 from above
cellrow 1, col 1
ways1 0 0
Column 1 has no cell on its left, so the only way in is from above. The count 1 stays as it is.
grid11rockways array1col 11col 20col 3this cell0+1=10 from above, 1 from the left → 1
cellrow 1, col 2
ways1 1 0
Before it changes, this column's entry still holds the count for the cell above (0); the entry on its left was just updated for this row (1). An open cell adds them: 1 route.
grid111rockways array1col 11col 21col 3this cell0+1=10 from above, 1 from the left → 1
cellrow 1, col 3
ways1 1 1
Before it changes, this column's entry still holds the count for the cell above (0); the entry on its left was just updated for this row (1). An open cell adds them: 1 route.
grid1111rockways array1col 11col 21col 3this cell1→1no left cellleft edge: keeps 1 from above
cellrow 2, col 1
ways1 1 1
Column 1 has no cell on its left, so the only way in is from above. The count 1 stays as it is.
grid1111rockways array1col 10col 21col 3this cell1→0rockrock → 0 routes pass through
cellrow 2, col 2
ways1 0 1
This cell is a rock, so no route can stand on it. Its count becomes 0, which throws away the 1 route carried down from above and gives the cells to its right and below nothing to add.
grid1111rock1ways array1col 10col 21col 3this cell1+0=11 from above, 0 from the left → 1
cellrow 2, col 3
ways1 0 1
Before it changes, this column's entry still holds the count for the cell above (1); the entry on its left was just updated for this row (0). An open cell adds them: 1 route.
grid1111rock11ways array1col 10col 21col 3this cell1→1no left cellleft edge: keeps 1 from above
cellrow 3, col 1
ways1 0 1
Column 1 has no cell on its left, so the only way in is from above. The count 1 stays as it is.
grid1111rock111ways array1col 11col 21col 3this cell0+1=10 from above, 1 from the left → 1
cellrow 3, col 2
ways1 1 1
Before it changes, this column's entry still holds the count for the cell above (0); the entry on its left was just updated for this row (1). An open cell adds them: 1 route.
grid1111rock1112ways array1col 11col 22col 3this cell1+1=21 from above, 1 from the left → 2
cellrow 3, col 3
ways1 1 2
Before it changes, this column's entry still holds the count for the cell above (1); the entry on its left was just updated for this row (1). An open cell adds them: 2 routes.
grid1111rock1112ways array1col 11col 22col 3this cell+=2 routes reach the corner
answer2
After the last row, the final entry is the count for the bottom-right cell: 2 routes, none of which touch a rock.
05

Common pitfalls

Filling the whole top row and left column with 1

✗ Wrong
ways = [1] * n
✓ Right
ways = [0] * n
ways[0] = 1

Starting the top row as all 1s ignores a rock in that row. For [[0, 1, 0], [0, 0, 0]] the cell after the rock would keep its 1, giving 2 routes, while the only real route goes down first and then right twice: the answer is 1.

Not checking the start cell

✗ Wrong
ways[0] = 1
for row in grid:
    for j in range(1, n):
✓ Right
ways[0] = 1
for row in grid:
    for j in range(n):

If the loop starts at column 1, a rock in column 0 is never seen. For [[1, 0], [0, 0]] the robot starts on a rock, so the answer must be 0, but the untouched 1 in column 0 flows on and the code returns 2.

06

Edge cases

Rock on the finish, such as [[0, 0], [0, 1]]

The last cell visited sets ways[n - 1] = 0, so the answer is 0 with no extra check.

Counts larger than the answer

A cell that is later cut off from the finish can hold far more routes than the final answer, which is the only number the problem bounds. C++ and Java keep the counts in 64-bit types for that reason.

07

Complexity

Time
O(m · n)
Space
O(n)
Every cell is visited once with one comparison and at most one addition. Only one row of counts is kept.
08

Unique Paths II FAQ

Can I store the counts in the grid itself?

Yes. Overwrite each cell with its route count (rocks become 0, the first open start cell becomes 1) and the extra memory drops to O(1). It changes the input, though, which some interviewers ask you not to do.

Does the combinations formula from the open-grid version still work?

No. C(m + n − 2, m − 1) counts every right/down route, including the ones through rocks. You would have to subtract routes through each rock and add back routes through pairs of rocks, which is far harder than the table. The open grid is Unique Paths.

What about a recursive solution with memo?

Counting from a cell to the finish as count(below) + count(right), with rocks and off-grid cells returning 0, gives the same answer. With a memo it is O(m · n) too, but recursion can go 199 calls deep on a 100 × 100 grid.