題目
一個機器人位於一個 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. 向下 -> 向下 -> 向右 -> 向右
鏈接:https://leetcode-cn.com/problems/unique-paths-ii
解題記錄
- 通過動態規劃求解
- 如果是1的話改點的dp爲0,即不做處理
- 如果爲0的話,因爲是通過左邊或者上邊到達,因此
dp[i][j]= dp[i-1][j] + dp[i][j-1]
- 爲了不判斷邊界,在dp數組左邊和上邊添加了一層
/**
* @author ffzs
* @describe
* @date 2020/7/6
*/
public class Solution {
public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
int y = obstacleGrid.length;
int x = obstacleGrid[0].length;
int[][] dp = new int[y+1][x+1];
dp[0][1] = 1;
System.out.println(Arrays.deepToString(dp));
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
if (obstacleGrid[i][j] == 0){
dp[i+1][j+1] = dp[i+1][j] + dp[i][j+1];
}
}
}
return dp[y][x];
}
public static void main(String[] args) {
// int[][] obstacleGrid = {{0,0,0}, {0,1,0}, {0,0,0}};
int[][] obstacleGrid = {{0,0}};
System.out.println(uniquePathsWithObstacles(obstacleGrid));
}
}