LeetCode OJ:Unique Paths II(唯一路径II)
2015-10-22 16:37
411 查看
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
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
这个与前面那个题目基本上差不多,具体就是多了障碍,实际上遇到障碍的话把到该点的路径的数目置为0就可以了,其他的基本上与前面相同:
java版本的代码如下所示:
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] ]
这个与前面那个题目基本上差不多,具体就是多了障碍,实际上遇到障碍的话把到该点的路径的数目置为0就可以了,其他的基本上与前面相同:
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { if(obstacleGrid.size() == 0 || obstacleGrid[0].size() == 0) return 0; vector<vector<int>> res(obstacleGrid.size(), vector<int>(obstacleGrid[0].size(), 0)); int maxHor = obstacleGrid.size(); int maxVer = obstacleGrid[0].size(); res[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1; for(int i = 1; i < maxHor; ++i){ res[i][0] = obstacleGrid[i][0] == 1 ? 0 : res[i - 1][0]; } for(int j = 1; j < maxVer; ++j){ res[0][j] = obstacleGrid[0][j] == 1 ? 0 : res[0][j - 1]; } for(int i = 1; i < maxHor; ++i){ for(int j = 1; j < maxVer; ++j){ res[i][j] = obstacleGrid[i][j] == 1 ? 0 : res[i - 1][j] + res[i][j - 1]; } } return res[maxHor - 1][maxVer - 1]; } };
java版本的代码如下所示:
public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { if(obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0; int [][] grid = new int [obstacleGrid.length][obstacleGrid[0].length]; grid[0][0] = obstacleGrid[0][0]==1 ? 0 : 1; for(int i = 1; i < obstacleGrid.length; ++i){ grid[i][0] = obstacleGrid[i][0]==1? 0 : grid[i-1][0]; } for(int i = 1; i < obstacleGrid[0].length; ++i){ grid[0][i] = obstacleGrid[0][i]==1? 0 : grid[0][i-1]; } for(int i = 1; i < obstacleGrid.length; ++i){ for(int j = 1; j < obstacleGrid[0].length; ++j){ grid[i][j] = obstacleGrid[i][j]==1? 0 : (grid[i-1][j] + grid[i][j-1]); } } return grid[obstacleGrid.length-1][obstacleGrid[0].length-1]; } }
相关文章推荐
- 线程池大小设置与BlockingQueue的三种实现区别(顶)
- easyui-helloworld
- 关于UIScrollView无限循环滑动
- IOS笔记UI--Block传值
- 【腾讯Bugly干货分享】Android UI:机智的远程动态更新策略
- UIWrapContent
- YuiDoc与JsDoc通用标签归纳汇总
- android 获取string.xml中的value
- UVa1342 That Nice Euler Circuit(欧拉函数)
- 使用easyui控件中的easyui-datetimebox时间控件,获取时间值的方法
- HDU_5504 GT and sequence
- HDU_5504 GT and sequence
- @GeneratedValue
- Add docking and floating support easely and quickly with DockExtender
- UIPickerView的简单使用
- 关于UIView的autoresizingMask属性的研究
- java.sql.SQLException: Incorrect string value
- LeetCode OJ:Unique Paths(唯一路径)
- Requested a new session but one was in progress
- Metal Tips and Techniques