public class Solution {
// f[i][j] = how many paths from (0,0) to (i,j)
// f[i][j] = f[i - 1][j] + f[i][j - 1]
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) {
return 0;
}
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] f = new int[m][n];
for (int i = 0; i < m; i++) {
if (obstacleGrid[i][0] == 1 || (i > 0 && f[i - 1][0] == 0)) {
f[i][0] = 0;
} else {
f[i][0] = 1;
}
}
for (int i = 0; i < n; i++) {
if (obstacleGrid[0][i] == 1 || (i > 0 && f[0][i - 1] == 0)) {
f[0][i] = 0;
} else {
f[0][i] = 1;
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] == 1) {
f[i][j] = 0;
} else {
f[i][j] = f[i - 1][j] + f[i][j - 1];
}
}
}
return f[m - 1][n - 1];
}
}
2016年7月26日星期二
[LeetCode] #63 Unique Paths II
订阅:
博文评论 (Atom)
没有评论:
发表评论