[LeetCode]63 不同的路径总数之二
来源:互联网 发布:python怎么滤波图片 编辑:程序博客网 时间:2024/06/07 22:52
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]; }};
0 0
- [LeetCode]63 不同的路径总数之二
- [LeetCode]62 不同的路径总数
- LeetCode OJ 之 Unique Paths II(不同路径 - 二)
- LeetCode OJ 之 Unique Paths (不同路径)
- LeetCode OJ 之 Unique Binary Search Trees II (不同的二叉搜索树 - 二)
- [LeetCode]95 不同二分查找树之二
- 1142 Relations dp n个数的不同大小关系总数
- SPOJ694 && SPOJ705 ——不同子串的总数
- oracle 查询同一字段不同状态下面的总数
- Oracle统计某一字段在不同值下的总数
- LeetCode OJ 之 Path Sum II (路径和 - 二)
- 不同的路径
- 题目 :不同的路径
- LintCode -- 不同的路径
- LintCode 不同的路径
- 不同的路径
- 不同的路径 II
- LintCode_不同的路径
- ZOJ-3780-Paint the Grid Again【11th浙江省赛】
- Android上面做Flash播放器
- HDU 3790 最短路径问题(双重Dijkstra算法)
- Mybatis入门实例(优化版本)(2) - SSM(二)
- 菜鸟成长记录——2015-2016半年总
- [LeetCode]63 不同的路径总数之二
- html5的特性和js sdk 在微信平台上的应用
- 【每日算法】图算法(遍历&MST&最短路径&拓扑排序)
- NYOJ——聪明的kk
- Unity3D surf 函数,简单折射
- 博客迁移
- Switch结构的分析_20160225
- oracle计算时间差的问题
- 单例设计模式