当前位置:网站首页>【动态规划】不同路径2
【动态规划】不同路径2
2022-04-23 06:11:00 【小风_】
链接 https://leetcode-cn.com/problems/unique-paths-ii
一个机器人位于一个 m x n 网格的左上角,机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角,现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?
定义: d p [ i ] [ j ] dp[i][j] dp[i][j]表示从索引号 ( 0 , 0 ) (0,0) (0,0)到索引号 ( i , j ) (i,j) (i,j)的路径走法的数量
边界:第一行和第一列, d p [ 0 ] [ 0 ] dp[0][0] dp[0][0]只能是1。同时,由于只能下走或右走,因此第一行和第一列都是可直接计算的,为1,如果遇到障碍,为0。
状态转移方程: d p [ i ] [ j ] = { d p [ i − 1 ] [ j ] + d p [ i ] [ j − 1 ] , o b s t a c l e G r i d [ i ] [ j ] = 0 0 , o b s t a c l e G r i d [ i ] [ j ] ≠ 0 d p[i][j]= \begin{cases}d p[i-1][j]+dp[i][j-1], & obstacleGrid[i][j]~=\operatorname 0 \\ 0, & obstacleGrid[i][j]~≠\operatorname 0\end{cases} dp[i][j]={ dp[i−1][j]+dp[i][j−1],0,obstacleGrid[i][j] =0obstacleGrid[i][j] =0
说明:当前值,等于上一行和左一列的和,如果遇到障碍,为0
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[0 for i in range(n)] for j in range(m)]
for i in range(n):
if obstacleGrid[0][i]==1:
break
dp[0][i] = 1
for i in range(m):
if obstacleGrid[i][0]==1:
break
dp[i][0] = 1
for i in range(1, m):
for j in range(1, n):
if obstacleGrid[i][j] == 0:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m-1][n-1]
版权声明
本文为[小风_]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_33952811/article/details/118961779
边栏推荐
- 给女朋友写个微信双开小工具
- PaddleOCR 图片文字提取
- Miscellaneous learning
- Using queue to realize stack
- Component based learning (1) idea and Implementation
- [sm8150] [pixel4] LCD driver
- 项目,怎么打包
- MySQL5. 7 insert Chinese data and report an error: ` incorrect string value: '\ xb8 \ XDF \ AE \ xf9 \ X80 at row 1`
- Project, how to package
- 电脑关机程序
猜你喜欢
iTOP4412 LCD背光驱动(PWM)
Android interview Online Economic encyclopedia [constantly updating...]
Cancel remote dependency and use local dependency
ThreadLocal, just look at me!
个人博客网站搭建
【2021年新书推荐】Learn WinUI 3.0
adb shell top 命令详解
Itop4412 HDMI display (4.0.3_r1)
【2021年新书推荐】Enterprise Application Development with C# 9 and .NET 5
[2021 book recommendation] effortless app development with Oracle visual builder
随机推荐
电脑关机程序
[Andorid] 通过JNI实现kernel与app进行spi通讯
this.getOptions is not a function
中国各省会城市经纬度位置
xcode 编译速度慢的解决办法
Reading notes - activity
MySQL5.7插入中文数据,报错:`Incorrect string value: ‘\xB8\xDF\xAE\xF9\x80 at row 1`
BottomSheetDialogFragment + ViewPager+Fragment+RecyclerView 滑动问题
Google AdMob advertising learning
[exynos4412] [itop4412] [android-k] add product options
【2021年新书推荐】Practical Node-RED Programming
常见的正则表达式
[2021 book recommendation] artistic intelligence for IOT Cookbook
Three methods to realize the rotation of ImageView with its own center as the origin
[SM8150][Pixel4]LCD驱动
去掉状态栏
Android暴露组件——被忽略的组件安全
Component based learning (3) path and group annotations in arouter
三子棋小游戏
MySQL notes 3_ Restraint_ Primary key constraint