如果道路上有障礙,機器人從起點到終點有多少條不同的路徑,只能向右或者向下走。0表示道路通行,1表示有障礙。
注意點:
起點如果也有障礙,那就無法出發了例子:
輸入:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
輸出: 2
思路跟 Unique Paths 是一樣的,不過要分類討論一下障礙的情況,如果當前格子是障礙,那麼到達該格子的路徑數目是0,因為無法到達,如果是普通格子,那麼由左邊和右邊的格子相加。
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
if obstacleGrid[0][0] == 1:
return 0
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[0 for __ in range(n)] for __ in range(m)]
dp[0][0] = 1
for i in range(1, m):
dp[i][0] = dp[i - 1][0] if obstacleGrid[i][0] == 0 else 0
for j in range(1, n):
dp[0][j] = dp[0][j - 1] if obstacleGrid[0][j] == 0 else 0
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[m - 1][n - 1]
if __name__ == "__main__":
assert Solution().uniquePathsWithObstacles([
[0, 0, 0],
[0, 1, 0],
[0, 0, 0]
]) == 2