代码随想录算法训练营第39天|62.不同路径 63. 不同路径 II

文章介绍了使用动态规划解决LeetCode中的62题和63题,即在网格中找到不同的路径。在62题中,主要讨论了如何初始化二维数组以计算不同路径的数量;而在63题中,增加了障碍物的因素,需要处理不能通过的格子,同样利用动态规划求解。
摘要由CSDN通过智能技术生成

62.不同路径 

代码随想录

视频讲解:动态规划中如何初始化很重要!| LeetCode:62.不同路径_哔哩哔哩_bilibili

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        #set dp for m*n table
        dp= [[1]*n]*m
        #go from the index 1 of column and row because there is only one way to
        #reach the first row and the first column location . 
        for i in range(1,m):
            for j in range(1,n):
                #only can reach to current point from top and left
                dp[i][j]=dp[i-1][j]+dp[i][j-1]
        #return the last location number. 
        return dp[-1][-1]

63. 不同路径 II 

https://programmercarl.com/0063.%E4%B8%8D%E5%90%8C%E8%B7%AF%E5%BE%84II.htmlhttps://programmercarl.com/0063.%E4%B8%8D%E5%90%8C%E8%B7%AF%E5%BE%84II.html

视频讲解:动态规划,这次遇到障碍了| LeetCode:63. 不同路径 II_哔哩哔哩_bilibili

class Solution(object):
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        #set up a dp table
        row = len(obstacleGrid)
        col = len(obstacleGrid[0])
        dp = [[0 for _ in range(col)] for _ in range(row)]
        #set base number as 1 unless the corresponding dp is 0
        dp[0][0] = 0 if obstacleGrid[0][0] == 1 else 1
        #return 0 if the start is 0
        if dp[0][0] == 0:
            return 0  
        # for the first row, if the current location is 1, go to a break, which 
        #means the grid after the cur cannot be reached 
        for i in range(1, col):
            if obstacleGrid[0][i] == 1:
                break
            dp[0][i] = 1

        # for the first col, do the same thing as pricessing the row
        for i in range(1, row):
            if obstacleGrid[i][0] == 1:
                break
            dp[i][0] = 1
        #for dp[i][j],we add the value from top and left to get the different
        #ways to reach cur
        for i in range(1, row):
            for j in range(1, col):
                if obstacleGrid[i][j] == 0:
                    dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
        #return the result 
        return dp[-1][-1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值