image.png
(图片来源https://leetcode-cn.com/problems/unique-paths-ii/
)
日期 | 是否一次通过 | comment |
---|---|---|
2020-02-28 | 0 | 忘了处理grid边缘有1的情况 |
初始化;交换;排障
- row 向
public int uniquePathsWithObstacles1(int[][] obstacleGrid) {
int rowL = obstacleGrid.length;
int colL = obstacleGrid[0].length;
int[] dp = new int[rowL];
// 初始化
for(int i=0; i<rowL; i++) {
if(obstacleGrid[i][0] != 0) {
dp[i] = 0;
break;
}
dp[i] = 1;
}
// 遍历grid
for (int j=1; j<colL; j++) {
if(obstacleGrid[0][j] != 0) { // grid边缘处理
dp[0] = 0;
}
for (int i=1; i < rowL; i++) {
if (obstacleGrid[i][j] != 0) {
dp[i] = 0;
} else { // j > 0 if (dp[i - 1] != 0)
dp[i] += dp[i - 1];
}
}
}
return dp[rowL - 1];
}
- col向
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int rowL = obstacleGrid.length;
int colL = obstacleGrid[0].length;
int[] dp = new int[colL];
for(int j=0; j<colL; j++) {
if(obstacleGrid[0][j] != 0) {
dp[j] = 0;
break;
}
dp[j] = 1;
}
for (int i=1; i<rowL; i++) {
if(obstacleGrid[i][0] != 0) {
dp[0] = 0;
}
for (int j=1; j < colL; j++) {
if (obstacleGrid[i][j] != 0) {
dp[j] = 0;
} else { // j > 0
dp[j] += dp[j - 1];
}
}
}
return dp[colL - 1];
}
网友评论