leetcode 63. Unique Paths II

本文探讨了在存在障碍物的网格中,机器人从左上角到右下角的路径规划问题。通过动态规划方法,详细解析了如何计算在3x3网格中,避开中间障碍物到达目标的路径数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Input:
[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

分析:
这道题是之前那道 Unique Paths的延伸,在路径中加了一些障碍物,还是用动态规划Dynamic Programming来解,不同的是当遇到为1的点,将该位置的dp数组中的值清零,其余和之前那道题并没有什么区别

def uniquePathsWithObstacles(self, obgrid):
    path = [0]*len(obgrid[0])
    if obgrid[0][0] == 1:
        return 0
     path[0]=1
     for i in range(len(obgrid)):
         for j in range(len(obgrid[0])):
             if obgrid[i][j] == 1:
                  path[j] = 0
             elif j > 0:
                 path[j] += path[j-1]
    return path[len(obgrid[0])-1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值