LeetCode | Unique Paths II(唯一路径II)
2014-08-18 15:57
423 查看
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
in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
The total number of unique paths is
Note: m and n will be at most 100.
题目解析:
这道题是上一题的扩展:LeetCode | Unique Paths
注意的是先初始化第一行和第一列,从左到右初始化的过程中,碰到一个结点有障碍物,那么从该点开始之后的路径值都为0。
当遍历内部结点的时候,没有障碍物就是左边和上面两个路径值的和。不用刻意判断左边和上面是否有障碍物,有的话路径值已经赋为0了,直接相加即可。
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
1and
0respectively
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.
题目解析:
这道题是上一题的扩展:LeetCode | Unique Paths
注意的是先初始化第一行和第一列,从左到右初始化的过程中,碰到一个结点有障碍物,那么从该点开始之后的路径值都为0。
当遍历内部结点的时候,没有障碍物就是左边和上面两个路径值的和。不用刻意判断左边和上面是否有障碍物,有的话路径值已经赋为0了,直接相加即可。
class Solution { public: int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { vector<vector<int> >res; int row = obstacleGrid.size(); if(row == 0) return 0; int col = obstacleGrid[0].size(); if(col == 0) return 0; for(int i = 0;i < row;i++){ vector<int> tmp = vector<int> (col,0); res.push_back(tmp); } //一开始就有阻碍物的话,就一定不可达 if(obstacleGrid[0][0] == 1) return 0; //初始化,第一行和第一列,当碰到有一个障碍物的时候,后面的或下面的就全为0 for(int i = 0;i < row;i++){ if(obstacleGrid[i][0] == 0){ res[i][0] = 1; }else break; } for(int j = 0;j < col;j++){ if(obstacleGrid[0][j] == 0) res[0][j] = 1; else break; } //如果这个位置没有障碍物,那么其路径为右边过来的和上面过来的之和, //如果有障碍物就为0,因为已经初始化了,就不用赋值了 for(int i = 1;i < row;i++){ for(int j = 1;j < col;j++){ if(obstacleGrid[i][j] == 0) res[i][j] = res[i-1][j] + res[i][j-1]; } } return res[row-1][col-1]; } };
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【063-Unique Paths II(唯一路径问题II)】
- [LeetCode]20. Unique Paths II唯一路径
- 【LeetCode-面试算法经典-Java实现】【063-Unique Paths II(唯一路径问题II)】
- [LeetCode]19. Unique Paths唯一路径
- LeetCode题库解答与分析——#63.不同路径IIUniquePathsII
- LeetCode OJ:Unique Paths II(唯一路径II)
- [Leetcode] unique paths ii 独特路径
- [LeetCode] Unique Paths II 起点与终点确定的路径数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 I & II
- Unique Paths II 求在矩阵里从左上走到右下的总方法数(有障碍)@LeetCode
- [leetcode刷题系列]Unique Paths II