Unique Paths II
- Lintcode : 115 / Leetcode : 63
- Level : Easy
Problem
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.
Example
Example 1:
Input: [[0]]
Output: 1
Example 2:
Input: [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
Explanation:
Only 2 different path.
Notice
m and n will be at most 100.
Concept & Algorithm
Time Complexity & Space Complexity
time : O(m n)
space: O(m n)
Answer
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
dp[0][0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (obstacleGrid[i][j] == 1) {
dp[i][j] = 0;
}else if (i == 0 && j == 0) {
continue;
}else if (i == 0) {
dp[i][j] = dp[i][j - 1];
}else if (j == 0) {
dp[i][j] = dp[i - 1][j];
}else {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
return dp[m - 1][n - 1];
}
};
沒有留言:
張貼留言