LeetCode 63. Unique Paths II
Question
A robot is located at the top-left corner of a m x n
grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and space is marked as 1
and 0
respectively in the grid.
Example 1:
1 | Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] |
Example 2:
1 | Input: obstacleGrid = [[0,1],[0,0]] |
Constraints:
m == obstacleGrid.length
n == obstacleGrid[i].length
1 <= m, n <= 100
obstacleGrid[i][j]
is0
or1
.
Source: https://leetcode.com/problems/unique-paths-ii/
Solution
For grids occupied by obstacles, we set their number of unique paths to zero. Note that when initializing the first row and column of the DP array, an obstacle will make itself and all following grids unreachable.
1 | // Time Complexity O(mn), Space Complexity O(mn) |
LeetCode 63. Unique Paths II