LeetCode 63 Unique Path II
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
.
Note: m and n will be at most 100.
DifficultyMedium
Similar Problems
[LeetCode 62] Unique Paths M
Analysis
There is a little difference with the Unique Paths.
Be carefule of the cases that the obstacle
is set in the starting position and the destination position, meaning no way to reach the destination, in that case, we should return 0.
Beside, when we encounter obstacle[i][j] == 1
, we need to set dp[j] = 0
.
Idea 1
Transition functions:
dp[i]][j] = dp[i-1][j] + dp[i][j-1] if obstacle[i][j] == 0
= 0 if obstacle[i][j] == 1
Idea 2
Using 1D rolling array to reduce space usage
Solutions
- DP with 1D Array
class Solution{
public:
int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
int m = obstacleGrid.size();
if(m == 0) return 0;
int n = obstacleGrid[0].size();
if(obstacleGrid[0][0] == 1) return 0; // don't forget this case
vector<int> dp(n, 0);
dp[0] = 1;
for(int i = 0; i < m; i++){
for(int j = 0; j < n;j++){
if(obstacleGrid[i][j] == 1)
dp[j] = 0;
else if(j > 0)
dp[j] = dp[j] + dp[j - 1];
}
}
return dp[n-1];
}
};
- Go solution (1D Array)
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
m := len(obstacleGrid)
if m == 0 {
return 0
}
n := len(obstacleGrid[0])
if obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1 {
return 0
}
dp := make([]int, n)
dp[0] = 1
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if obstacleGrid[i][j] == 1 {
dp[j] = 0
} else if j > 0 {
dp[j] += dp[j-1]
}
}
}
return dp[n-1]
}