思路:另建一个整形数组,第一行和第一列赋值,用于存放各个点的路径,然后将障碍点的路径数设置为0即可。根本还是P[i][j] = P[i-1][j] + P[i][j-1]
代码:
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] paths = new int[m][n];
if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1) {
return 0;
}
// 分别paths将第一行、第一列权值置1
for(int i=0; i<m; i++) {
if(obstacleGrid[i][0] != 1) {
paths[i][0] = 1;
} else { // 其后的所有元素都赋值0
for(int k=i; k<m; k++)
paths[k][0] = 0;
break;
}
}
for(int j=0; j<n; j++) {
if(obstacleGrid[0][j] != 1) {
paths[0][j] = 1;
} else {
for(int k=j; k<n; k++)
paths[0][k] = 0;
break;
}
}
// 注意要把边界考虑进去,因为边界可能出现障碍
for(int i=1; i<m; i++) {
for(int j=1; j<n; j++) {
if(obstacleGrid[i][j] != 1) {
paths[i][j] = paths[i-1][j] + paths[i][j-1];
} else {
paths[i][j] = 0;
}
}
}
return paths[m-1][n-1];
}
}