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.
SOULUTION 1:
跟LeetCode: Unique Paths 解题报告 相比,只不过是判断一下当前是不是block,如果是block,直接设置D[i][j] 是0就好了 也就是不可达。 同样在3分钟之内Bug free 秒答,哦耶!
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
//
if (obstacleGrid == null || obstacleGrid.length == || obstacleGrid[].length == ) {
return ;
} int rows = obstacleGrid.length;
int cols = obstacleGrid[].length; int[][] D = new int[rows][cols]; for (int i = ; i < rows; i++) {
for (int j = ; j < cols; j++) {
D[i][j] = ;
if (obstacleGrid[i][j] == ) {
D[i][j] = ;
} else {
if (i == && j == ) {
D[i][j] = ;
} if (i != ) {
D[i][j] += D[i - ][j];
} if (j != ) {
D[i][j] += D[i][j - ];
}
}
}
} return D[rows - ][cols - ];
}
}