题目:
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.
题目分析:
上一题
Unique Paths参考http://blog.csdn.net/qq_31663969/article/details/79027692,这题思路和上一题相似,都是使用动态规划,但是如果有一格有障碍这格的dp值要设为0,另外边界条件也不一样,之前是上和左边的dp值都是1,现在如果途中有一格是障碍则要把它及它之后的dp值都设为0
动态规划方程为if (obstacleGrid[i][j] == 0) dp[i][j] = dp[i-1][j] + dp[i][j-1];
else dp[i][j] = 0;
else dp[i][j] = 0;
c++代码:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if (n == 1 && m == 1 && obstacleGrid[0][0] == 0) return 1;
if (n == 1 && m == 1 && obstacleGrid[0][0] == 1) return 0;
int** dp = new int*[m];
for (int i = 0; i < m; i++) {
dp[i] = new int[n];
}
int flag = 0;
for (int i = 0; i < m; i++) {
if (flag == 0 && obstacleGrid[i][0] == 0) {dp[i][0] = 1;}
if (flag == 1 || obstacleGrid[i][0] == 1) {
dp[i][0] = 0;
flag = 1;
}
}
flag = 0;
for (int j = 0; j < n; j++) {
if (flag == 0 && obstacleGrid[0][j] == 0) {dp[0][j] = 1;}
if (flag == 1 || obstacleGrid[0][j] == 1) {
dp[0][j] = 0;
flag = 1;
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j] == 0) dp[i][j] = dp[i-1][j] + dp[i][j-1];
else dp[i][j] = 0;
}
}
return dp[m-1][n-1];
}
};