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
.
在第i个位置上设置一个障碍物后,说明位置i到最后一个格子这些路都没法走 为0
所以说明,在初始条件时,如果一旦遇到障碍物,障碍物后面所有格子的走法都是0
再看求解过程,当然按照上一题的分析dp[i][j] = dp[i-1][j] + dp[i][j-1] 的递推式依然成立.碰到了障碍物,那么这时的到这里的走法应该设为0,因为机器人只能向下走或者向右走,所以到这个点就无法通过。
时间O(m*n) 空间O(m*n)
public class Solution {
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) {
return 0;
}
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int [][] sum = new int [m][n];
for (int i = 0; i < m; i++) {
if (obstacleGrid[i][0] != 1) {
sum[i][0] = 1;
} else {
break;//后面所有的都无法到达所以break
}
}
for (int j = 0; j < n; j++) {
if (obstacleGrid[0][j] != 1) {
sum[0][j] = 1;
} else {
break;
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] != 1) {
sum[i][j] = sum[i-1][j] + sum[i][j-1];
} else {
sum[i][j] = 0;
}
}
}
return sum[m-1][n-1];
}
}