Follow up for "Unique Paths":
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.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2
.
Note: m and n will be at most 100.
思路:将两边和1初始化即可。
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
if obstacleGrid[-1][-1]==1 or obstacleGrid[0][0]==1:
return 0
m,n=len(obstacleGrid),len(obstacleGrid[0])
dp=[[0]*n for i in range(m)]
for j in range(n):
if obstacleGrid[0][j]==0:
dp[0][j]=1
else:
for jj in range(j,n):
dp[0][jj]=0
break
for i in range(m):
if obstacleGrid[i][0]==0:
dp[i][0]=1
else:
for ii in range(i,m):
dp[ii][0]=0
break
for i in range(1,m):
for j in range(1,n):
dp[i][j]=dp[i-1][j]+dp[i][j-1] if obstacleGrid[i][j]!=1 else 0
return dp[-1][-1]