You are given an m x n integer grid grid. A robot starts at the top-left cell grid[0][0] and tries to reach the bottom-right cell grid[m - 1][n - 1]. On each move the robot goes exactly one cell down or one cell to the right.
A cell holding 1 is an obstacle and a cell holding 0 is open. The robot can never enter an obstacle cell.
Return the number of distinct paths the robot can take to reach the bottom-right corner.
Function Signature
def unique_paths_with_obstacles(grid: list[list[int]]) -> int:
Rules
-
grid[i][j] == 1
marks an obstacle and
grid[i][j] == 0
marks an open cell.
-
A path may not start on, pass through or end on an obstacle. If
grid[0][0]
or
grid[m - 1][n - 1]
is
1
, return 0.
-
Two paths are different when their sequences of moves differ. For a 1 by 1 grid holding
0
, the path with no moves counts, so the answer is 1.
Constraints
-
m == len(grid)
-
n == len(grid[i])
-
1 <= m, n <= 100
-
grid[i][j]
is
0
or
1
-
The answer is at most
2 * 10^9
.
Examples
Input: grid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
+---+---+---+
| 0 | 0 | 0 |
+---+---+---+
| 0 | 1 | 0 |
+---+---+---+
| 0 | 0 | 0 |
+---+---+---+
The obstacle sits in the center of the 3 by 3 grid. Of the 6 right-and-down paths, 4 pass through the center, which leaves Right, Right, Down, Down and Down, Down, Right, Right.
Input: grid = [[0,1],[0,0]]
Output: 1
The top-right cell is blocked, so the only path is Down, then Right.
Input: grid = [[0,0],[1,1],[0,0]]
Output: 0
The whole middle row is blocked. The robot never moves up, so every path would have to cross that row, and none can.