Programming Camp – Algorithm Training Camp – Day 39

1. Unique Paths (Leetcode Number: 62)

While initializing the array, all the values of the first row as well as the first column are 1 as the solution is unique.

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        i, j = 0, 0
        dp = [ [1] * n for _ in range(m)]


        for i in range(1, m):
            for j in range(1, n):
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
        
        return dp[m - 1][n - 1]

2. Unique Paths II (Leetcode Number: 63)

The values of the first column elements and first row elements need to be flipped (0 - > 1 and 1 -> 0). The original 1 means there is an obstacle, after being converted to 0, it means the number of the paths to this grid is 0 as it's blocked. So this grid wouldn't be a part of the calculation of possible paths for next grid.

class Solution(object):
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        row = len(obstacleGrid)
        col = len(obstacleGrid[0])
        if obstacleGrid[0][0] == 1:
            return 0

        obstacleGrid[0][0] = 1
        
        for i in range(1, row):
            obstacleGrid[i][0] = int(obstacleGrid[i][0] == 0 and obstacleGrid[i -1 ][0] == 1)
        
        for j in range(1, col):
            obstacleGrid[0][j] = int(obstacleGrid[0][j] == 0 and obstacleGrid[0][j - 1])
        
        for i in range(1, row):
            for j in range(1, col):
                if obstacleGrid[i][j] == 0:
                    obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1]
                else:
                    obstacleGrid[i][j] = 0
                  
        
        return obstacleGrid[row - 1][col - 1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值