Unique Paths II
medium
dynamic-programming
matrix
You are given an m x n integer grid obstacleGrid where 0 marks an empty cell and 1 marks an obstacle. Starting from the top-left cell, return the number of distinct paths to the bottom-right cell, moving only right or down and never stepping onto an obstacle.
If the start or the destination cell is an obstacle, there are 0 valid paths.
Input / output
- Input:
obstacleGrid: int[][] - Output:
int(number of obstacle-free paths)
Examples
obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]returns2; the single middle obstacle leaves two ways around it.obstacleGrid = [[0,1],[0,0]]returns1.obstacleGrid = [[1]]returns0because the start itself is blocked.
Constraints
1 <= m, n <= 100obstacleGrid[i][j]is0or1- The answer fits in a 32-bit signed integer.
Follow-up
The full grid of subresults is easy to write but uses O(m*n) memory. Can you compute the answer with only O(n) extra space by reusing a single row?
Examples
Example 1
Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
Example 2
Input: obstacleGrid = [[0,1],[0,0]]
Output: 1
Example 3
Input: obstacleGrid = [[1]]
Output: 0