LeetCode Unique Paths II

LeetCode解题之Unique Paths II


原题

假设道路上有障碍,机器人从起点到终点有多少条不同的路径,仅仅能向右或者向下走。

0表示道路通行,1表示有障碍。

robot

注意点:

  • 起点假设也有障碍。那就无法出发了

样例:

输入:
[
[0,0,0],
[0,1,0],
[0,0,0]
]

输出: 2

解题思路

思路跟 Unique Paths 是一样的,只是要分类讨论一下障碍的情况,假设当前格子是障碍,那么到达该格子的路径数目是0。由于无法到达,假设是普通格子,那么由左边和右边的格子相加。

AC源代码

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://www.cnblogs.com/cynchanpin/p/7217931.html