LeetCode--Unique Paths II
来源:互联网 发布:mac 播放器 自动字幕 编辑:程序博客网 时间:2024/06/04 19:40
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
.
Note: m and n will be at most 100.
这道题紧接着Unique Path一题,与那道题不一样的地方就是这次地图中的格子有的是有障碍不能走的,即标记为1的地方,其它的与Unique Path都一样,还是从左上角走到右下角一共有多少种方法,每一步只能向下或者向右移动一个格子。
其实总体的思路和上一题都是一样的,不过细节问题还要多加留意,首先,如果传入的地图是空的,就要直接返回0,如果入口就有障碍,即obstacleGrid[0][0]的值为1的话,也要直接返回0。
初始化也和上一题不同,上一题是地图的上边界和左边界的对应的格子到达方法数的值都是1,而这道题对于地图的上边界和左边界的每一个格子,如果它前面有障碍或者它本身含有障碍的的话,那么到达这个格子的方法数要赋值为0。
举几个例子解释一下前面有障碍的含义:
第一行第一列的格子值为0,第一行第二列的值为1的话,那么到达第一行第二列,第三列,第四列,第五列一直到最后一列的方法数都为0,只有到达第一行第一列的值为1。
第一行第一列的格子值为0,第二行第一列的值为1的话,那么到达第二行第一列,第三行第一列,第四行第一列,第五行第一列直到最后一行的方法数都为0,只有到达第一行第一列的值为1。
搜索过程中核心代码也与上一题略有不同,这里要考虑目前搜索到的格子是不是含有障碍,含有障碍的话直接赋值为0,不含有的话就是ans[i][j] = ans[i-1][j]+ans[i][j-1]。
代码如下:
class Solution {public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { if (obstacleGrid.empty()) return 0; if (obstacleGrid[0][0] == 1) return 0; int row, col; row = obstacleGrid.size(); col = obstacleGrid[0].size(); int ans[101][101]; memset(ans, 0, sizeof(ans)); ans[0][0] = 1; for (int i = 1; i < row; i++) { if (ans[i-1][0] != 0 && obstacleGrid[i][0] != 1) ans[i][0] = 1; } for (int i = 1; i < col; i++) { if (ans[0][i-1] != 0 && obstacleGrid[0][i] != 1) ans[0][i] = 1; } for(int i = 1; i < row; i++) for(int j = 1; j < col; j++) { if (obstacleGrid[i][j] == 1) { ans[i][j] = 0;} else {ans[i][j] = ans[i-1][j]+ans[i][j-1]; }} return ans[row-1][col-1]; }};
- LeetCode: Unique Paths II
- [Leetcode] Unique Paths II
- LeetCode : Unique Paths II
- [LeetCode] Unique Paths II
- [LeetCode]Unique Paths II
- [leetcode]Unique Paths II
- LeetCode-Unique Paths II
- [leetcode] Unique Paths II
- LeetCode - Unique Paths II
- LeetCode:Unique Paths II
- 【LeetCode】Unique Paths II
- leetcode Unique Paths II
- LeetCode Unique Paths II
- LeetCode | Unique Paths II
- Leetcode: Unique Paths II
- LeetCode Unique Paths II
- Unique Paths II -- LeetCode
- [LeetCode] Unique Paths II
- JDBC学习笔记(2)——数据库连接
- Mangos源码分析(4):服务器结构探讨之继续世界服
- 7·RHCSA升级内核
- Ubuntu: eclipse tomcat unknown version of tomcat was specified
- Thinking in java 读书笔记(二、for循环,标签,switch语句)
- LeetCode--Unique Paths II
- mysql如何使用命令行运行sql文件
- 文件下载
- Android 8.0 画中画demo
- 面试题错题总结
- Mysql创建Function报1418错误
- 阿里云播放器SDK的正确打开方式 | 功能、架构与应用(一)
- 人工智障学习笔记——机器学习(5)朴素贝叶斯
- itext生成PDF,并弹出下载框提示下载