原题
https://leetcode.com/problems/unique-paths-ii/
解法
动态规划. 注意edge case, 当障碍物在起点时, 直接返回0, 初始化二维数组dp,dp[i][j]代表到达grid[i][j]点的路径数, dp[0][0]等于1. 由于此题有障碍物, 那么从第0行和第0列开始, 遇到障碍物则跳出循环. 然后从第1行和第一列开始, 状态转移方程是:
dp[i][j] = dp[i-1][j] + dp[i][j-1] if obstacleGrid[i][j] != 1 else 0
Time: O(mn)
Space: O(mn)
代码
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: 'List[List[int]]') -> 'int':
# edge case
if obstacleGrid[0][0] == 1: return 0
m, n = len(obstacleGrid), len(obstacleGrid[0])
dp = [[0]*n for i in range(m)]
dp[0][0] = 1
for c in range(1, n):
if obstacleGrid[0][c] != 1:
dp[0][c] = 1
else:
break
for r in range(1, m):
if obstacleGrid[r][0] != 1:
dp[r][0] = 1
else:
break
for r in range(1, m):
for c in range(1, n):
if obstacleGrid[r][c] != 1:
dp[r][c] = dp[r-1][c] + dp[r][c-1]
return dp[-1][-1]