代码链接:https://leetcode-cn.com/problems/unique-paths-ii/solution/ru-he-li-jie-dong-tai-by-chenchen-bh-hew4/
方法一:二维数组
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[0] * n for _ in range(m)]
# (0, 0)格子可能有障碍物
dp[0][0] = 0 if obstacleGrid[0][0] else 1
for i in range(1, m):
if obstacleGrid[i][0] == 1 or dp[i-1][0] == 0:
dp[i][0] = 0
else:
dp[i][0] = 1
for i in range(1, n):
if obstacleGrid[0][i] == 1 or dp[0][i-1] == 0:
dp[0][i] = 0
else:
dp[0][i] = 1
for i in range(1, m):
for j in range(1, n):
if obstacleGrid[i][j] == 1: # 如果当前格子是障碍物
dp[i][j] = 0
else:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
方法二:一维数组:
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [0]*n
dp[0] = 0 if obstacleGrid[0][0] else 1
for i in range(m):
for j in range(n):
if obstacleGrid[i][j] == 1:
dp[j] = 0
elif obstacleGrid[i][j] == 0 and j>=1:
dp[j] = dp[j-1] + dp[j]
return dp[-1]