Unique Paths II
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.
思路:建立paths[n][m]存到每一点的方法。具体:先看初始状态会不会受到障碍物的影响,假设棋盘只有一行,若其中 i 位置有障碍物,则 i 到这一行最后都不能走了,则从 i 到最后都设置为0;再假设棋盘只有一列,同理,若有一个位置 j 有障碍物,则 j 之后都为0;再从i=1 和 j =1 循环考察到每一位置的方法,由于机器人只能往下和右走,p[ i ] [ j ] = p[i - 1][ j ] + p[ i ][j - 1], 若棋盘中有障碍物,此处走法设置为0,否则按公式相加,最后输出p[n - 1][m - 1]。
代码:
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) {
return 0;
}
int n = obstacleGrid.length;
int m = obstacleGrid[0].length;
int[][] paths = new int[n][m];
for (int i = 0; i < n; i++) {
if (obstacleGrid[i][0] != 1) {
paths[i][0] = 1;
} else {
break;
}
}
for (int j = 0; j < m; j++) {
if (obstacleGrid[0][j] != 1) {
paths[0][j] = 1;
} else {
break;
}
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (obstacleGrid[i][j] == 1) {
paths[i][j] = 0;
} else {
paths[i][j] = paths[i - 1][j] + paths[i][j - 1];
}
}
}
return paths[n - 1][m - 1];
}
}