Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1
and 0
respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[ [0,0,0], [0,1,0], [0,0,0] ]
The total number of unique paths is 2
.
--- an extension of LeetCode 62. DP problem but need to pay more attention to the obstacle.
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if(obstacleGrid.size() == 0) return 0;
if(obstacleGrid[0].size() == 0) return 0;
int cols = obstacleGrid[0].size();
int rows = obstacleGrid.size();
vector< vector<int> > matrix(rows, vector<int>(cols, 0));
for(int i = 0; i < cols; ++i) {
if(obstacleGrid[0][i] != 1) {
matrix[0][i] = 1;
} else {break;} // if obstacle, the left over path would be 0.
}
for(int j = 0; j < rows; ++j) {
if(obstacleGrid[j][0] != 1) {
matrix[j][0] = 1;
} else {break;} // if obstacle, the left over path would be 0.
}
for(int i = 1; i < rows; ++i) {
for(int j = 1; j < cols; ++j) {
if(obstacleGrid[i][j] != 1) {
matrix[i][j] = matrix[i-1][j] + matrix[i][j-1]; // only if it is not an obstacle.
} else {
matrix[i][j] = 0;
}
}
}
return matrix[rows - 1][cols - 1];
}
A variation: Find the minimum cost from first column to last column.
For example:
[1, 2, 3]
[2, 0, 0]
[1, 0, 0] the minimum cost is 1. The idea is to use DP. If there is only one column, it is easy. If there are two columns, there are three directions to go, up, down, right, thus, it need two sweeps.
int miniCost(vector< vector<int> >& matrix) {
int m = matrix.size();
int n = matrix[0].size();
if(m == 0 || n == 0) return 0;
vector<int> dp(m, 0);
for(int i = 0; i < m; ++i) {
dp[i] = matrix[i][n-1];
}
for(int i = n - 2; i >= 0; --i) {
dp[0] += matrix[0][i]; // there is only one choice here.
for(int j = 1; j < m; ++j) {
dp[j] = min(dp[j-1], dp[j]) + matrix[j][i]; // go down or go left.
}
for(int j = m - 2; j >= 0; --j) {
dp[j] = min(dp[j], dp[j + 1] + matrix[j][i]); // go up
}
}
int mincost = INT_MAX;
for(int i = 0; i < m; ++i) mincost = min(mincost, dp[0]);
return mincost;
}
int main(void) {
vector< vector<int> > matrix {
{0, 1, 2},
{0, 1, 2},
{2, 0, 0}};
cout << miniCost(matrix) << endl;
}