Leetcode 63. Different paths II
1 title description ( Leetcode topic Link )
A robot located in a left corner mxn grid (starting point figure below labeled "Start").
The robot can only move one step to the right or down. Robot trying to reach the bottom right corner of the grid (in the following figure labeled "Finish").
Now consider the grid obstacle (obstacle and the empty grid positions are represented by 1 and 0). So how many different paths from top left to bottom right corner there will be?
Example:
输入:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
输出: 2
解释:
3x3 网格的正中间有一个障碍物。
从左上角到右下角一共有 2 条不同的路径:
1. 向右 -> 向右 -> 向下 -> 向下
2. 向下 -> 向下 -> 向右 -> 向右
2 solution to a problem
Title were filled obstacle on the basis of the different paths 1, this time need only fill an array of DP when the first determining whether the location is 0, if 0 is set to the position 0, the state transition equation DP has not changed:
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
if obstacleGrid[0][0] == 1: //判断入口是否有障碍物
return 0
m = len(obstacleGrid)
n = len(obstacleGrid[0])
DP = [([0] * n) for i in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
DP[i][j] = 1
continue
if obstacleGrid[i][j] == 1:
DP[i][j] = 0
else:
DP[i][j] = DP[i-1][j]+DP[i][j-1]
return DP[m-1][n-1]