Unique Paths II
The key idea
The number of ways to reach a cell equals the ways to reach the cell above it plus the ways to reach the cell to its left, because the robot can only arrive from those two directions. An obstacle cell is unreachable, so its count is forced to
0, which naturally cancels any path that would have crossed it.Problem
You are given an m x n integer array obstacleGrid. A robot starts at the top-left corner (grid[0][0]) and wants to reach the bottom-right corner. The robot can only move either down or right at any point in time.
An obstacle and an empty space are marked as 1 and 0 respectively in obstacleGrid. A path that the robot takes cannot include any square that is an obstacle.
Return the number of possible unique paths that the robot can take to reach the bottom-right corner.
The testcases are generated so that the answer will be less than or equal to 2 * 10^9.
Constraints
m == obstacleGrid.lengthn == obstacleGrid[i].length1 <= m, n <= 100obstacleGrid[i][j]is0or1
Examples
Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
Input: obstacleGrid = [[0,1],[0,0]]
Output: 1
Complexity
Time: O(m*n) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Dynamic Programming problems
- Best Time to Buy and Sell StockEASY
- Best Time to Buy and Sell Stock IIIHARD
- Best Time to Buy and Sell Stock IVHARD
- Best Time to Buy and Sell Stock with CooldownMEDIUM
- Best Time to Buy and Sell Stock with Transaction FeeMEDIUM
- Burst BalloonsHARD
- Climbing StairsEASY
- Coin ChangeMEDIUM
- Coin Change IIMEDIUM
- Combination Sum IVMEDIUM
- Counting BitsEASY
- Decode WaysMEDIUM