本题是62题的稍微修改版,输入的地图用0表示可通行,用1表示障碍。
解题:同样有递归方法和动态规划的方法,递归方法仍然超时,不过还是放在这里。
代码:
递归方法:
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
self.res=0
self.find(obstacleGrid,0,0,len(obstacleGrid)-1,len(obstacleGrid[0])-1)
return self.res
def find(self,l,m,n,x,y):
if m==x+1 or n==y+1 or l[m][n]==1:
return
if m==x and n==y:
self.res+=1
return
self.find(l,m,n+1,x,y)
self.find(l,m+1,n,x,y)
动态规划:
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m, n = len(obstacleGrid), len(obstacleGrid[0])
dp = [[0] * n for _ in range(m)]
if obstacleGrid[0][0] == 0:
dp[0][0] = 1
for i in range(m):
for j in range(n):
if obstacleGrid[i][j] == 0:
if i == j == 0:
continue
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]