这一题由62题变化而来,如果理解了第62题,可以说这一题毫无难度,只需将数组中阻塞的点可通行的路线数量设为0即可。
public class Q63_Unique_Paths_II {
public static void main(String[] args) {
System.out.println(uniquePathsWithObstacles(new int[][]{{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}));
System.out.println(uniquePathsWithObstacles(new int[][]{{0, 1}, {0, 0}}));
}
public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
//m:行数;n:列数
int m = obstacleGrid.length, n = obstacleGrid[0].length;
int count[][] = new int[m][n];
for (int i = 0; i < m; i++) {
//阻塞点置为0,此路不通
if (obstacleGrid[i][0] == 1) {
for (int j = i; j < m; j++) {
count[i][0] = 0;
}
break;
} else {
count[i][0] = 1;
}
}
for (int i = 0; i < n; i++) {
//同上
if (obstacleGrid[0][i] == 1) {
for (int j = i; j < n; j++) {
count[0][j] = 0;
}
break;
} else {
count[0][i] = 1;
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
//同上
if (obstacleGrid[i][j] == 1) {
count[i][j] = 0;
} else {
count[i][j] = count[i - 1][j] + count[i][j - 1];
}
}
}
return count[m - 1][n - 1];
}
}