LeetCode筆記——63不同路徑Ⅱ
阿新 • • 發佈:2018-12-18
題目:
一個機器人位於一個 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. 向下 -> 向下 -> 向右 -> 向右
思路:思路和62題的思路相同,只不過再加上一個判斷。同時注意如何求矩陣的行列
程式碼:class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int rows = obstacleGrid.length;
int cols = obstacleGrid[0].length;
int[][] path = new int[rows][cols];
// int[][] path=new int[m][n];
path[0][0]= obstacleGrid[0][0] == 0 ? 1 : 0;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(i==0&&j==0)continue;
else if(i==0&&j!=0){
path[i][j]=obstacleGrid[i][j]==0?path[i][j-1]:0;
}
else if(i!=0&&j==0){
path[i][j]=obstacleGrid[i][j]==0?path[i-1][j]:0;
}
else path[i][j]=obstacleGrid[i][j]==0?path[i-1][j]+path[i][j-1]:0;
}
}
return path[rows-1][cols-1];
}
}