class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int row = obstacleGrid.length;
int colum = obstacleGrid[0].length;
if (obstacleGrid[0][0] == 1 || obstacleGrid[row - 1][colum - 1] == 1) return 0;
int[][] dp = new int[row][colum];
// 初始化第一行和第一列,值得注意的是在遇到障碍之后的dp数组值应该是0
for (int i = 0; i < row; i++) {
if (obstacleGrid[i][0] == 0){
dp[i][0] = 1;
} else {
break;
}
}
for (int j = 0; j < colum; j++) {
if (obstacleGrid[0][j] == 0) {
dp[0][j] = 1;
} else {
break;
}
}
for (int i = 1; i < row; i++) {
for (int j = 1; j < colum; j++) {
if (obstacleGrid[i][j] == 0) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
// for (int i = 1; i < row; i++) {
// for (int j = 1; j < colum; j++) {
// System.out.print(dp[i][j] + " ");
// }
// System.out.println();
// }
return dp[row - 1][colum - 1];
}
}
leetcode 63. 不同路径 II
最新推荐文章于 2024-05-04 03:45:26 发布