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.
62题的followup,在路径上添加了障碍物,障碍物无法通过。还用上一题动态规划的思路解决,但是需要注意两个地方:1、第一行或第一列,如果某个位置是障碍物了,那么它右边或者下边就都无法到达了;2、除了第一行和第一列,其余位置,如果是障碍,那么它无法到达,这个位置的路径数也是0。
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) {
return 0;
}
if (obstacleGrid[0][0] == 1) {
return 0;
}
int n = obstacleGrid.length;
int m = obstacleGrid[0].length;
int[][] dp = new int[n][m];
dp[0][0] = 1;
for (int i = 1; i < n; i++) {
if (obstacleGrid[i][0] == 0) {
dp[i][0] = 1;
} else {
break;
}
}
for (int i = 1; i < m; i++) {
if (obstacleGrid[0][i] == 0) {
dp[0][i] = 1;
} else {
break;
}
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (obstacleGrid[i][j] == 1) {
continue;
}
if (obstacleGrid[i-1][j] == 0) {
dp[i][j] += dp[i-1][j];
}
if (obstacleGrid[i][j-1] == 0) {
dp[i][j] += dp[i][j-1];
}
}
}
return dp[n-1][m-1];
}