标签:
如果道路上有障碍,机器人从起点到终点有多少条不同的路径,只能向右或者向下走。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
欢迎查看我的[Github] (https://github.com/gavinfish/LeetCode-Python)(https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
标签:
原文地址:http://blog.csdn.net/u013291394/article/details/50531113