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
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:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
分析:
这道题是之前那道 Unique Paths的延伸,在路径中加了一些障碍物,还是用动态规划Dynamic Programming来解,不同的是当遇到为1的点,将该位置的dp数组中的值清零,其余和之前那道题并没有什么区别
def uniquePathsWithObstacles(self, obgrid):
path = [0]*len(obgrid[0])
if obgrid[0][0] == 1:
return 0
path[0]=1
for i in range(len(obgrid)):
for j in range(len(obgrid[0])):
if obgrid[i][j] == 1:
path[j] = 0
elif j > 0:
path[j] += path[j-1]
return path[len(obgrid[0])-1]