leetcode 63. Unique Paths II
来源:互联网 发布:淘宝店铺换身份证 编辑:程序博客网 时间:2024/06/05 06:03
题目
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.
思路
跟62题思路差不多
代码
package leetcodeArray;import java.util.Arrays;public class Leetcode63UniquePaths2 { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length, n = obstacleGrid[0].length; if(obstacleGrid[m-1][n - 1] == 1){ return 0; } Integer [][] path = new Integer[m][n]; Boolean flag = true; for(int i = 0; i < m; ++i){ if(obstacleGrid[i][0] == 0 && flag) path[i][0] = 1; else{ path[i][0] = 0; flag = false; } } flag = true; for(int i = 0; i < n; ++i){ if(obstacleGrid[0][i] == 0 && flag) path[0][i] = 1; else{ path[0][i] = 0; flag = false; } } for(int i = 1; i < m; ++i){ for(int j = 1; j < n; ++j){ if(obstacleGrid[i - 1][j] ==1 && obstacleGrid[i][j - 1] == 0){ path[i][j] = path[i][j - 1]; } else if(obstacleGrid[i][j - 1] == 1 && obstacleGrid[i - 1][j] == 0){ path[i][j] = path[i - 1][j]; } else if(obstacleGrid[i][j - 1] == 0 && obstacleGrid[i - 1][j] == 0){ path[i][j] = path[i - 1][j] + path[i][j - 1]; } else{ path[i][j] = 0; } System.out.println(path[i][j]); } } return path[m - 1][n - 1]; } public static void main(String[] args){ int[][] grib = {{1, 0}}; Leetcode63UniquePaths2 test = new Leetcode63UniquePaths2(); System.out.println(test.uniquePathsWithObstacles(grib)); }}
他山之玉
public int uniquePathsWithObstacles(int[][] obstacleGrid) { int width = obstacleGrid[0].length; int[] dp = new int[width]; dp[0] = 1; for (int[] row : obstacleGrid) { for (int j = 0; j < width; j++) { if (row[j] == 1) dp[j] = 0; else if (j > 0) dp[j] += dp[j - 1]; } } return dp[width - 1];}
阅读全文
0 0
- LeetCode --- 63. Unique Paths II
- LeetCode 63.Unique Paths II
- [leetcode] 63.Unique Paths II
- [leetcode] 63.Unique Paths II
- Leetcode 63. Unique Paths II
- LeetCode 63. Unique Paths II
- [leetcode] 63. Unique Paths II
- leetcode 63. Unique Paths II
- 63. Unique Paths II LeetCode
- LeetCode 63. Unique Paths II
- [LeetCode]63. Unique Paths II
- leetcode 63. Unique Paths II
- LeetCode *** 63. Unique Paths II
- leetcode 63. Unique Paths II
- Leetcode:63. Unique Paths II
- LeetCode 63. Unique Paths II
- leetcode 63.Unique Paths II
- LeetCode 63. Unique Paths II
- hdu6082-度度熊与邪恶大魔王
- android 性能优化相关整理
- 2017多校-6
- final
- 数据结构实验之二叉树三:统计叶子数
- leetcode 63. Unique Paths II
- (11)存储引擎
- 抗不过,还是实名认证了下。。。
- 数值孔径大小对微透镜匀光的影响
- js正则表达式
- 对MVC、MVVM开发模式的理解和总结
- 为什么使用MQ
- 爬虫实践---Scrapy-爬取慕课网热门课程
- SVM入门(五)线性分类器的求解——问题的描述Part2