【leetcode系列】【算法】【中等】不同路径 II

题目:

题目链接: https://leetcode-cn.com/problems/unique-paths-ii/

解题思路:

如果上一题:不同路径 使用的是DP算法解题的,则这一题只需要稍加修改就好了

修改的地方为:

  1. 初始化时,除了[0][0]点,其余点都初始化为0
  2. 在更新dp[i][j]之前,先判断当前位置是否有障碍物;如果有,则更新为0,如果没有,则正常更新

代码实现:

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        if 0 == len(obstacleGrid) or 0 == len(obstacleGrid[0]):
            return 0

        path = [[0 for _ in range(0, len(obstacleGrid[0]))] for _ in range(0, len(obstacleGrid))]
        if 0 == obstacleGrid[0][0]:
            path[0][0] = 1

        for i in range(0, len(obstacleGrid)):
            for j in range(0, len(obstacleGrid[i])):
                if obstacleGrid[i][j] == 1:
                    path[i][j] = 0
                    continue
                    
                if i >= 1:
                    path[i][j] += path[i - 1][j]
                    
                if j >= 1:
                    path[i][j] += path[i][j - 1]
                    
        return path[-1][-1]
发布了100 篇原创文章 · 获赞 4 · 访问量 1492

猜你喜欢

转载自blog.csdn.net/songyuwen0808/article/details/105235892