[LeetCode]63 不同的路径总数之二
2016-02-28 13:42
465 查看
Unique Paths II(不同的路径总数之二)
【难度:Medium】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.
LeetCode 62题的扩展,为机器人增加了障碍物,0表示空地,1表示障碍,同样求从左上角到右下角不同的走法总数。
解题思路
在62题的基础上解决这个问题,但需要考虑的是,机器人不能简单地向下或向右走,要判断是否有障碍物,因此左边界和上边界的初始化也要根据上一个点的状态来设置,同样使用动态规划来完成。c++代码如下:
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { if (obstacleGrid.empty()) return 0; //入口有障碍的话,直接返回 if (obstacleGrid[0][0] == 1) return 0; int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<vector<int>> path(m,vector<int>(n,0)); //入口点走法只有1种。 path[0][0] = 1; for (int i = 1; i < m; i++) { //左边界,如果上一点可行并且当前点没有障碍物,那么该点可走 if (path[i-1][0] != 0 && obstacleGrid[i][0] != 1) path[i][0] = 1; } for (int i = 1; i < n; i++) { //上边界与左边界情况同理 if (path[0][i-1] != 0 && obstacleGrid[0][i] != 1) path[0][i] = 1; } for (int i = 1; i < m; i++) for (int j = 1; j < n; j++) //动态规划,当前点无障碍物则与62题处理方法一致 if (obstacleGrid[i][j] != 1) path[i][j] = path[i-1][j]+path[i][j-1]; return path[m-1][n-1]; } };
相关文章推荐
- Android上面做Flash播放器
- HDU 3790 最短路径问题(双重Dijkstra算法)
- Angularjs在初始化未完毕时出现闪烁的解决办法
- TCP三次握手连接与四次握手断开
- TypeScript Modules(模块)
- ZOJ-3780-Paint the Grid Again【11th浙江省赛】
- Visual Studio配置VLFeat库
- JavaScript--Map和Set介绍
- c语言:求三个数中的最大值(双分支结构)
- java 知识体系
- 排它平方数
- Gradle笔记——构建基础
- 存储器的保护(一)——《x86汇编语言:从实模式到保护模式》读书笔记18
- C语言(函数与宏)
- Android Studio初体验之导入eclipse项目
- nodejs request & response 对象
- 工具:Office for Mac 2016破解
- 从闭包案例中学习闭包的作用,会不会由你。
- NYOJ 又见拦截导弹
- 【前端】Sublime text3 插件HTML/CSS/JS prettify 格式化代码