題目:
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.
題解:
這道題大體想法跟Unique Path是一樣的。
只是要單獨考慮下障礙物對整個棋盤的影響。
先看看初始條件會不會受到障礙物的影響。
假設整個棋盤只有一行,那麼在第i個位置上設定一個障礙物後,說明位置i到最後一個格子這些路都沒法走了。
如果整個棋盤只有一列,那麼第i位置上的障礙物,也會影響從第i位置往後的路。
所以說明,在初始條件時,如果一旦遇到障礙物,障礙物後面所有格子的走法都是0。
再看求解過程,當然按照上一題的分析dp[i][j] = dp[i-1][j] + dp[i][j-1] 的遞推式依然成立(機器人只能向下或者向右走嘛)。但是,一旦碰到了障礙物,那麼這時的到這裡的走法應該設為0,因為機器人只能向下走或者向右走,所以到這個點就無法通過。
處理完障礙物的特殊問題,依照unique paths改一下程式碼就好。
程式碼如下:
1 public int uniquePathsWithObstacles(int[][] obstacleGrid) {
2 int m = obstacleGrid.length;
3 int n = obstacleGrid[0].length;
4
5 if(m==0||n == 0)
6 return 0;
7
8 if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1)
9 return 0;
10
11 int[][] dp = new int[m][n];
12
13 dp[0][0] = 1;
14 for(int i = 1; i < n; i++){
15 if(obstacleGrid[0][i] == 1)
16 dp[0][i] = 0;
17 else
18 dp[0][i] = dp[0][i-1];
19 }
20
21 for(int i = 1; i < m; i++){
22 if(obstacleGrid[i][0] == 1)
23 dp[i][0] = 0;
24 else
25 dp[i][0] = dp[i-1][0];
26 }
27
28 for(int i = 1; i < m; i++){
29 for(int j = 1; j < n; j++){
30 if(obstacleGrid[i][j] == 1)
31 dp[i][j] = 0;
32 else
33 dp[i][j] = dp[i][j-1] + dp[i-1][j];
34 }
35 }
36 return dp[m-1][n-1];
37 }
2 int m = obstacleGrid.length;
3 int n = obstacleGrid[0].length;
4
5 if(m==0||n == 0)
6 return 0;
7
8 if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1)
9 return 0;
10
11 int[][] dp = new int[m][n];
12
13 dp[0][0] = 1;
14 for(int i = 1; i < n; i++){
15 if(obstacleGrid[0][i] == 1)
16 dp[0][i] = 0;
17 else
18 dp[0][i] = dp[0][i-1];
19 }
20
21 for(int i = 1; i < m; i++){
22 if(obstacleGrid[i][0] == 1)
23 dp[i][0] = 0;
24 else
25 dp[i][0] = dp[i-1][0];
26 }
27
28 for(int i = 1; i < m; i++){
29 for(int j = 1; j < n; j++){
30 if(obstacleGrid[i][j] == 1)
31 dp[i][j] = 0;
32 else
33 dp[i][j] = dp[i][j-1] + dp[i-1][j];
34 }
35 }
36 return dp[m-1][n-1];
37 }