问题:
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.
这个问题是LeetCode 62. Unique Paths的后续问题。
思路基本一致,同样可以利用动态划归来解决,只是在计算当前位置的结果时,判断一下数组的值是否为1。
代码示例:
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null) {
return 0;
}
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
if (m == 0 || n ==0) {
return 0;
}
//第1个位置为1,显然没法继续玩耍了
if (obstacleGrid[0][0] == 1) {
return 0;
}
int[][] rst = new int[m+1][n+1];
//初始化
for (int i = 0; i <= m; ++i) {
rst[m][0] = 0;
}
for (int j = 0; j <= n; ++j) {
rst[0][j] = 0;
}
rst[1][1] = 1;
//与之前的思路一致,只是需要判断数组对应位置是否为1
//为1时,结果置为0
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (obstacleGrid[i-1][j-1] == 1) {
rst[i][j] = 0;
} else {
rst[i][j] = rst[i][j-1] + rst[i-1][j] + rst[i][j];
}
}
}
return rst[m][n];
}
}