[LeetCode]Unique Paths II
2015-04-06 16:43
218 查看
该题和之前的题目之间的区别就是某些单元是不可达的,这可以加上判断语句即可
算法1:
算法1:
public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int pathsNum = 0,m = obstacleGrid.length,n=obstacleGrid[0].length; if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1)return 0; int [][] paths = new int[m] ; for(int i = 0; i< m; i ++){ for(int j = 0; j < n; j ++){ if(i > 0 && j > 0){ if(obstacleGrid[i][j-1] == 1 && obstacleGrid[i-1][j] ==0){ paths[i][j] = paths[i-1][j]; }else if(obstacleGrid[i-1][j] == 1 && obstacleGrid[i][j-1] == 0){ paths[i][j] = paths[i][j-1]; }else if(obstacleGrid[i-1][j] == 0 && obstacleGrid[i][j-1] == 0){ paths[i][j] = paths[i][j-1] + paths[i-1][j]; }else { paths[i][j] = 0; } }else if(i > 0 && j == 0){ if(obstacleGrid[i-1][j] == 0){ paths[i][j] = paths[i-1][j]; }else { paths[i][j] = 0; } }else if(i == 0 && j > 0){ if(obstacleGrid[i][j-1] == 0){ paths[i][j] = paths[i][j-1]; }else { paths[i][j] = 0; } }else { if(obstacleGrid[0][0] == 1) return 0; else paths[0][0] = 1; } } } return paths[m-1][n-1]; } }感觉自己做的太复杂了,别人的简单版本如下:
public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { if(obstacleGrid == null || obstacleGrid.length==0 || obstacleGrid[0].length==0) return 0; int[] res = new int[obstacleGrid[0].length]; res[0] = 1; for(int i=0;i<obstacleGrid.length;i++) { for(int j=0;j<obstacleGrid[0].length;j++) { if(obstacleGrid[i][j]==1) { res[j]=0; } else { if(j>0) res[j] += res[j-1]; } } } return res[obstacleGrid[0].length-1]; } }
相关文章推荐
- LeetCode | Unique Paths II(唯一路径II)
- [LeetCode] 124: Unique Paths II
- [leetcode 63] Unique Paths II
- 【LeetCode】Unique Paths I && II
- LeetCode--Unique Paths II
- [LeetCode] Unique Paths II
- leetcode---Unique Paths II---dp
- [LeetCode]20. Unique Paths II唯一路径
- leetcode oj java Unique Paths II
- [LeetCode] Unique Paths II
- LeetCode Unique Paths II
- [LeetCode]Unique Paths I & II
- [Leetcode]Unique Paths II
- (leetcode)Unique Paths II
- [LeetCode] Unique Paths II
- leetcode 63: Unique Paths II
- Leetcode133: Unique Paths II
- LeetCode63——Unique Paths II
- [LeetCode]Unique Paths II@python
- LeetCode 63 Unique Paths II