Unique Paths II
来源:互联网 发布:陕西广电网络悟空宽带 编辑:程序博客网 时间:2024/06/10 18:19
题目原型:
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 Paths 类似,只是增加了障碍物的判断,具体思路是在原来的基础上判断如果此格为1,表示是障碍物,不存在有几种方法可行,直接置为0。
public int uniquePathsWithObstacles(int[][] obstacleGrid){if(obstacleGrid==null||obstacleGrid.length==0)return 0;int m = obstacleGrid.length;//数组行长int n = obstacleGrid[0].length;//数组列宽//若左上角第一个数为1和右下角最后一个数为1,表示走不通if(obstacleGrid[m-1][n-1]==1||obstacleGrid[0][0]==1)return 0;//初始化第一行和第一列,由于这两列的特殊化,只能从左到右或者从上到下走,所以一旦碰到障碍物则以下的都走不通了int startIndex = -1;for(int i = 0;i<m;i++){if(obstacleGrid[i][0]==1){obstacleGrid[i][0] = 0;startIndex = i;}else{if(startIndex==-1)obstacleGrid[i][0] = 1;elseobstacleGrid[i][0] = 0;}}startIndex = -1;//此处i从1开始for(int i = 1;i<n;i++){if(obstacleGrid[0][i]==1){obstacleGrid[0][i] = 0;startIndex = i;}else{if(startIndex==-1)obstacleGrid[0][i] = 1;elseobstacleGrid[0][i] = 0;}}//注意判断,如果此格为1,表示是障碍物,不存在有几种方法可行,直接置为0for(int i = 1;i<m;i++)for(int j = 1;j<n;j++){if(obstacleGrid[i][j]==1)obstacleGrid[i][j] = 0;elseobstacleGrid[i][j] = obstacleGrid[i-1][j]+obstacleGrid[i][j-1];}return obstacleGrid[m-1][n-1];}
0 0
- Unique Paths & Unique Paths II
- Unique Paths &&Unique Paths II
- Unique Paths & Unique Paths II
- Unique Paths & Unique Paths II
- LeetCode: Unique Paths II
- [Leetcode] Unique Paths II
- LeetCode : Unique Paths II
- Unique Paths II
- [LeetCode] Unique Paths II
- unique paths II
- Unique Paths II
- [LeetCode]Unique Paths II
- Unique Paths II
- Unique Paths II
- Unique Paths II
- Unique Paths II
- [leetcode]Unique Paths II
- Unique Paths II
- Android 深入解析selector
- 几个知识点,有时间的时候研究下
- 微信公众平台开发之刮刮卡
- abap几个函数
- 春天到来会引起多方面的身体不适
- Unique Paths II
- Missing MySQL in PHPinfo on Ubuntu Linux
- JavaScript MVC 框架技术选型
- 第四周作业
- XtremeToolkitPro使用方法
- jxls操作 excel
- 如何去掉自定义dialog的背景与边框?
- CSS入门知识
- march28失败的组合