LeetCode 63
通过dp来解,每个格子进入的方法只有从他的左边和上边,那么所有的方法就是左边和上边方法的和。如果有障碍,那么就是0. 把数组扩展一行一列,这样容易来处理,省去写special case。
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
if not obstacleGrid: return 0
m = len(obstacleGrid)
n = len(obstacleGrid[0])
if obstacleGrid[0][0] == 1: return 0
dp = [[0]* (n+1) for i in range(0, m+1)]
dp[1][1] = 1
for i in range(1, m+1) :
for j in range(1, n+1) :
if (obstacleGrid[i-1][j-1] == 0):
dp[i][j] += dp[i-1][j] + dp[i][j-1]
return dp[m][n]
这个题目的扩展,980题:
使用dfs 然后 backtracking的方法
def uniquePathsIII(self, grid: List[List[int]]) -> int:
if grid == None: return 0
rc = len(grid)
cc = len(grid[0])
numberOfSpaces = 0
for i in range(0, rc):
for j in range(0, cc):
if (grid[i][j] == 1):
startR = i
startC = j
elif grid[i][j] == 0:
numberOfSpaces +=1
numberOfPaths = 0
directions = [[1,0],[-1,0], [0,1],[0,-1]]
def dfs(grid: List[List[int]], r: int, c:int, numberOfVisited: int):
nonlocal directions
nonlocal numberOfPaths
nonlocal numberOfSpaces
if (r<0) or (c < 0) or (r >= rc) or (c >= cc) or grid[r][c] == -1:
return
elif grid[r][c] == 2 and numberOfVisited > numberOfSpaces:
numberOfPaths +=1
tmp = grid[r][c]
grid[r][c] = -1
for d in directions:
dfs(grid, r+d[0], c+d[1], numberOfVisited + 1)
grid[r][c] = tmp
dfs(grid, startR, startC, 0)
return numberOfPaths