python学习第8周(2): LeetCode.63. Unique Paths II 题解

本文探讨了在一个存在障碍物的网格中,机器人从起点到终点的不同路径数量的计算方法。利用动态规划思想,通过逐步更新每个格子的可达路径数来解决此问题。文章提供了一个Python实现方案。

这是一题动态规划的题目。若一个格子可达,则到达这个格子的路径数等于到达其上一个格子的路径数与到达其左格子的路径数的和;否则到达这个格子的路径数为0. 

 

题目:

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

Now consider if some obstacles are added to the grids. How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

Note: m and n will be at most 100.

 

题解:

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        #nums[i][j]表示到达(i, j)这个位置的路径数
        nums = obstacleGrid
        for j in range(0, len(obstacleGrid[0])):
            nums[0][j] = 1 - obstacleGrid[0][j]
        for i in range(1, len(obstacleGrid)):
            nums[i][0] = 0 if obstacleGrid[i][0] else nums[i-1][0]
            for j in range(1, len(obstacleGrid[i])):
                nums[i][j] = 0 if obstacleGrid[i][j] else nums[i-1][j] + nums[i][j-1]
        return nums[-1][-1]

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值