[Leetcode]@python 63. Unique Paths II

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


 题目大意:给定mxn的矩阵,0表示可以通过,1表示不可以通过,返回从(0,0)到(m,n)一共有多少种走法


 解题思路:考虑使用DP,给定一个矩阵a[i][j]表示从(0,0)到(i,j)共有多少种走法,动态转移方程:a[i][j] = a[i-1][j]+a[i][j-1],需注意考虑在矩阵边界的是情况


  代码(python):

class Solution(object):
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        m = len(obstacleGrid)
        n = len(obstacleGrid[0])
        ans = [[0 for i in range(n)] for j in range(m)]
        ans[0][0] = 1
        for i in range(m):
            for j in range(n):
                if obstacleGrid[i][j] == 1:
                    ans[i][j] = 0
                elif i != 0 and j == 0:
                    ans[i][j] = ans[i - 1][j]
                elif i == 0 and j != 0:
                    ans[i][j] = ans[i][j - 1]
                elif i != 0 and j != 0:
                    ans[i][j] = ans[i - 1][j] + ans[i][j - 1]
        return ans[m - 1][n - 1]
View Code
原文地址:https://www.cnblogs.com/slurm/p/5110203.html