63. Unique Paths II(有障碍的路径 动态规划)
2024-08-29 12:43:18
Follow up for "Unique Paths":
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.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2
.
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int rows = obstacleGrid.length;
int cols = obstacleGrid[0].length;
int[][] dp = new int[rows][cols]; for(int i = 0; i < rows;i++){
for (int j = 0; j < cols ;j++){
if(obstacleGrid[i][j]==1)
dp[i][j] = 0;
else{
if (i==0&& j==0)
dp[i][j] = 1;
else if (i==0)
dp[i][j] = dp[i][j-1]; //边界 else if (j == 0)
dp[i][j] = dp[i-1][j];
else
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
}
return dp[rows-1][cols-1];
}
}
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int rows = obstacleGrid.length;
int cols = obstacleGrid[0].length;
for(int i = 0; i < rows;i++){
for (int j = 0; j < cols ;j++){
if(obstacleGrid[i][j]==1)
obstacleGrid[i][j] = 0;
else if (i==0&& j==0)
obstacleGrid[i][j] = 1;
else if (i==0)
obstacleGrid[i][j] = obstacleGrid[i][j-1]*1; //边界,没有路径了,要么是0,要么是1 else if (j == 0)
obstacleGrid[i][j] = obstacleGrid[i-1][j]*1;
else
obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1];
}
}
return obstacleGrid[rows-1][cols-1];
}
}
最新文章
- Angular.js 的初步认识
- 移动网站中,用canvas,svg比用图片好?
- SDR和DDR1/2/3全系列频率对照表
- 移动开发 android 入门开发 阶段视频
- HTTP权威指南----缓存
- 如何用Maven创建一个普通Java项目
- Esper系列(三)Context和Group by
- SQLSERVER 列名无效
- Windows 8 卡在正在检查更新
- 2.3、Android Studio使用Layout Editor设计UI
- iOS监听模式系列之关于delegate(代理,委托)的学习
- kv.go
- Oracle 触发器和序列的创建和使用 (自动增长列)
- 【CXF】com.sun.xml.internal.ws.fault.ServerSOAPFaultException: Client received SOAP Faul
- eclipse 反编译
- 20155326刘美岑 2016-2017-2 《Java程序设计》第5周学习总结
- 第二阶段Sprint冲刺会议6
- WebGL射线拾取模型——八叉树优化
- redisAPI整理
- jmeter中类型转换,字符串,转数字型或浮点型
热门文章
- hdu 1253:胜利大逃亡(基础广搜BFS)
- loadruner11 socket脚本-10053错误
- python3----练习......
- 40 个顶级 jQuery 图片、内容滑块和幻灯片
- SPOJ 375 QTREE
- 单台centos7.3 虚拟机实现主从复制和哨兵集群
- 170411、java Socket通信的简单例子(UDP)
- Python全栈day28(上下文管理)
- Socket连接何时需要断开
- [iOS微博项目 - 4.3] - 设置每条微博边框样式