問題:數組
Follow up for "Unique Paths":ide
Now consider if some obstacles are added to the grids. How many unique paths would there be?spa
An obstacle and empty space is marked as 1
and 0
respectively in the grid.code
For example,it
There is one obstacle in the middle of a 3x3 grid as illustrated below.io
[ [0,0,0], [0,1,0], [0,0,0] ]
The total number of unique paths is 2
.class
Note: m and n will be at most 100.grid
解決:co
① 這道題大致想法跟Unique Path是同樣的。只是要單獨考慮下障礙物對整個棋盤的影響。錯誤
先看看初始條件會不會受到障礙物的影響:
再看求解過程:
dp[i][j] = dp[i-1][j] + dp[i][j-1] 的遞推式依然成立(機器人只能向下或者向右走)。可是,一旦碰到了障礙物,那麼這時的到這裏的走法應該設爲0,由於機器人只能向下走或者向右走,因此到這個點就沒法經過。
class Solution { //1ms
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
if(m == 0 || n == 0) return 0;
if(obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1) return 0; //須要判斷初始端點是否有障礙物,若是不判斷,有障礙物時返回結果錯誤
int[][] dp = new int[m][n];
dp[0][0] = 1;
for (int i = 1;i < n ;i ++ ) {//由於一旦遇到障礙物,障礙物後面全部格子的走法都是0,因此這麼寫。
if(obstacleGrid[0][i] == 1)
dp[0][i] = 0;
else
dp[0][i] = dp[0][i - 1];
}
for (int i = 1;i < m ;i ++ ) {
if(obstacleGrid[i][0] == 1)
dp[i][0] = 0;
else
dp[i][0] = dp[i - 1][0];
}
for (int i = 1;i < m ;i ++ ) {
for (int j = 1;j < n ;j ++ ) {
if(obstacleGrid[i][j] == 1)
dp[i][j] = 0;
else
dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
}
}
return dp[m - 1][n - 1];
}
}
② 使用一維數組。
初始數組dp爲[1,0,0],
i = 0:j = 0 :[1,0,0]; j = 1:[1,1,0]; j = 2:[1,1,1];//第一行
i = 1:j = 0:[1,1,1]; j = 1:[1,0,1]; j = 2:[1,0,1];//第二行
i = 2:j = 0:[1,0,1]; j = 1:[1,1,1]; j = 2:[1,1,2];//第三行
class Solution { // 1ms
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0)
return 0;
int[] dp= new int[obstacleGrid[0].length];
dp[0] = 1;
for(int i = 0;i < obstacleGrid.length;i ++){
for(int j = 0;j < obstacleGrid[0].length;j ++){
if(obstacleGrid[i][j] == 1){ dp[j] = 0; }else{ if(j > 0) dp[j] += dp[j - 1]; } } } return dp[obstacleGrid[0].length - 1]; } }