当前位置:网站首页>【动态规划】不同路径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
边栏推荐
猜你喜欢

Ffmpeg common commands

iTOP4412 LCD背光驱动(PWM)

./gradlew: Permission denied

取消远程依赖,用本地依赖

C connection of new world Internet of things cloud platform (simple understanding version)

Component based learning (3) path and group annotations in arouter

Fill the network gap

webView因证书问题显示一片空白

从0开始封装一套项目的网络请求框架

SSL/TLS应用示例
随机推荐
Using queue to realize stack
Itop4412 cannot display boot animation (4.0.3_r1)
.net加载字体时遇到 Failed to decode downloaded font:
取消远程依赖,用本地依赖
如何对多维矩阵进行标准化(基于numpy)
Recyclerview batch update view: notifyitemrangeinserted, notifyitemrangeremoved, notifyitemrangechanged
WebView displays a blank due to a certificate problem
Bottomsheetdialogfragment conflicts with listview recyclerview Scrollview sliding
What did you do during the internship
BottomSheetDialogFragment 与 ListView RecyclerView ScrollView 滑动冲突问题
[Exynos4412][iTOP4412][Android-K]添加产品选项
Easyui combobox 判断输入项是否存在于下拉列表中
Reading notes - activity
Android暴露组件——被忽略的组件安全
【2021年新书推荐】Practical IoT Hacking
[recommendation of new books in 2021] enterprise application development with C 9 and NET 5
中国各省会城市经纬度位置
Android清除应用缓存
adb shell 常用命令
c语言编写一个猜数字游戏编写