Unique Paths II
2014-03-28 09:27
176 查看
题目原型:
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.
基本思路:
和Unique Paths 类似,只是增加了障碍物的判断,具体思路是在原来的基础上判断如果此格为1,表示是障碍物,不存在有几种方法可行,直接置为0。
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
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.
基本思路:
和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; else obstacleGrid[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; else obstacleGrid[0][i] = 0; } } //注意判断,如果此格为1,表示是障碍物,不存在有几种方法可行,直接置为0 for(int i = 1;i<m;i++) for(int j = 1;j<n;j++) { if(obstacleGrid[i][j]==1) obstacleGrid[i][j] = 0; else obstacleGrid[i][j] = obstacleGrid[i-1][j]+obstacleGrid[i][j-1]; } return obstacleGrid[m-1][n-1]; }
相关文章推荐
- leetcode_Unique Paths II
- [leetcode][DP] Unique Paths II
- Unique Paths I,II
- LeetCode63:Unique Paths II
- 【LeetCode】Unique Paths II
- [leetcode刷题系列]Unique Paths II
- [LeetCode][Java] Unique Paths II
- LeetCode 63: Unique Paths II
- [Leetcode] #62#63 Unique Paths I & II
- 63. Unique Paths II
- Leetcode-Unique Paths II
- LEETCODE —— Unique Paths II [动态规划 Dynamic Programming]
- 63. Unique Paths II
- LeetCode(63)Unique Paths II
- Leetcode Unique Paths II
- [LeetCode] Unique Paths II
- LeetCode OJ:Unique Paths II(唯一路径II)
- leetcode Unique Paths II
- Unique Paths II
- [LeetCode] Unique Paths II