美文网首页
Unique Paths II

Unique Paths II

作者: 穿越那片海 | 来源:发表于2017-09-03 17:24 被阅读0次

medium, dynamic programming

Question

Unique Paths
加入路径上有一些障碍物,又该如何求解。
障碍物在矩阵中标记为1,其他标记为0

For example,
中间是障碍物的3X3网格如下
[
[0,0,0],
[0,1,0],
[0,0,0]
]
总共有2条路径.

Note: m and n will be at most 100.

Solution

Unique Paths解法类似,因为Bottom-Up的解法比Top-Down的解法更简单,这里使用Bottom-Up的方法。

class Solution(object):
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        m, n = len(obstacleGrid), len(obstacleGrid[0])
        mat = [[0 for j in range(n+1)] for i in range(m+1)]
        mat[m-1][n]=1
        for i in range(m-1, -1,-1):
            for j in range(n-1,-1,-1):
                mat[i][j] = 0 if obstacleGrid[i][j] == 1 else mat[i][j+1]+mat[i+1][j]
        return mat[0][0]

相关文章

网友评论

      本文标题: Unique Paths II

      本文链接:https://www.haomeiwen.com/subject/zajjjxtx.html