@author: sdubrz
@date: 2020.04.20
題號: 63
題目難度: 中等
考察內容: 動態規劃
原題鏈接 https://leetcode-cn.com/problems/unique-paths-ii/
題目的著作權歸領釦網絡所有,商業轉載請聯繫官方授權,非商業轉載請註明出處。
解題代碼轉載請聯繫 lwyz521604#163.com
一個機器人位於一個 m x n 網格的左上角 (起始點在下圖中標記爲“Start” )。
機器人每次只能向下或者向右移動一步。機器人試圖達到網格的右下角(在下圖中標記爲“Finish”)。
現在考慮網格中有障礙物。那麼從左上角到右下角將會有多少條不同的路徑?
網格中的障礙物和空位置分別用 1 和 0 來表示。
說明: m 和 n 的值均不超過 100。
示例 1:
輸入:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
輸出: 2
解釋:
3x3 網格的正中間有一個障礙物。
從左上角到右下角一共有 2 條不同的路徑:
1. 向右 -> 向右 -> 向下 -> 向下
2. 向下 -> 向下 -> 向右 -> 向右
通過次數54,072 提交次數164,780
解法
這道題相比於第62題來說,不同之處是加了障礙物。可以對第62題的解法稍作修改。在填路徑數量表之前,先判斷當前網格處是否爲障礙物,如果是則直接記到該網格的路徑數爲0,否則,按照第62題的方法計算。
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int n = obstacleGrid.length;
if(n==0){
return 0;
}
int m = obstacleGrid[0].length;
if(m==0){
return 0;
}
if(obstacleGrid[0][0]==1){
return 0;
}
int[][] count = new int[n][m];
boolean good = true;
for(int i=0; i<n; i++){
if(obstacleGrid[i][0]==1){
good = false;
}
if(good){
count[i][0] = 1;
}else{
count[i][0] = 0;
}
}
good = true;
for(int i=0; i<m; i++){
if(obstacleGrid[0][i]==1){
good = false;
}
if(good){
count[0][i] = 1;
}else{
count[0][i] = 0;
}
}
for(int i=1; i<n; i++){
for(int j=1; j<m; j++){
if(obstacleGrid[i][j]==1){
count[i][j] = 0;
continue;
}
count[i][j] = count[i-1][j]+count[i][j-1];
}
}
return count[n-1][m-1];
}
}
在 LeetCode 系統中提交的結果爲
執行結果: 通過 顯示詳情
執行用時 : 1 ms, 在所有 Java 提交中擊敗了 77.92% 的用戶
內存消耗 : 38.9 MB, 在所有 Java 提交中擊敗了 48.15% 的用戶
本文是在 LeetCode 刷題的筆記,如有不當之處歡迎通過留言或QQ賜教。