63. Unique Paths II
Last updated
Last updated
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Rightint uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { // time: O(m*n); space: O(m*n)
if (obstacleGrid.empty() || obstacleGrid[0].empty()) return 0;
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector<vector<long> > path(m, vector<long>(n, 0));
path[0][0] = obstacleGrid[0][0] == 0;
for (int i = 1; i < m; ++i) path[i][0] = obstacleGrid[i][0] == 0 && path[i - 1][0] == 1;
for (int j = 1; j < n; ++j) path[0][j] = obstacleGrid[0][j] == 0 && path[0][j - 1] == 1;
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
path[i][j] = (obstacleGrid[i][j] == 1) ? 0 : (path[i - 1][j] + path[i][j - 1]);
}
}
return (int)path.back().back();
}int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { // time: O(m*n); space: O(m*n)
if (obstacleGrid.empty() || obstacleGrid[0].empty()) return 0;
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector<vector<long> > path(m + 1, vector<long>(n + 1, 0));
path[0][1] = 1;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
path[i][j] = (obstacleGrid[i - 1][j - 1] == 1) ? 0 : (path[i - 1][j] + path[i][j - 1]);
}
}
return (int)path.back().back();
}int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { // time: O(m*n); space: O(n)
if (obstacleGrid.empty() || obstacleGrid[0].empty() || obstacleGrid[0][0] == 1) return 0;
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector<long> path(n, 0);
path[0] = 1;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (obstacleGrid[i][j] == 1) path[j] = 0;
else path[j] += (j >= 1) ? path[j - 1] : 0;
}
}
return (int)path.back();
}// Space Optimized Dynamic Programming
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { // time: O(m * n); space: O(n)
if (obstacleGrid.empty() || obstacleGrid[0].empty() || obstacleGrid[0][0] == 1) return 0;
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector<long> path(n + 1, 0);
path[1] = 1;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (obstacleGrid[i - 1][j - 1] == 1) path[j] = 0;
else path[j] += path[j - 1];
}
}
return (int)path.back();
}