Description
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 empty space is marked as 1 and 0 respectively in the grid.
Note: m and n will be at most 100.
Example
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
- Right -> Right -> Down -> Down
- Down -> Down -> Right -> Right
Submissions
这道题为上一题的进阶,添加了障碍物。因此可以采用另一种解题思路,本题中到达边缘位置只有一种选择,即要么在上面,要么在左面。到达非边缘位置有两种选择,即上面或左面。因此到达一个位置的路径数即前面的选择数叠加。直到到达右下角终点返回最终叠加总和。同时,添加了障碍物,即可将障碍物位置置为0,同理按上述思路解题即可。
实现代码如下:
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m, n = len(obstacleGrid), len(obstacleGrid[0])
res =[[0 for _ in range(n)] for _ in range(m)]
res[0][0] = 1
for i in range(m):
for j in range(n):
if obstacleGrid[i][j]==1:
res[i][j] = 0
else:
if i>0:
res[i][j] += res[i-1][j]
if j>0:
res[i][j] += res[i][j-1]
return res[-1][-1]