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.
Subscribe to see which companies asked this question
//这道题跟 Unique Paths 差不多,只是这道题给机器人加了障碍,不是每次都有两个选择(向右,向下)了。
//因为有了这个条件,所以 Unique Paths 中最后一个直接求组合的方法就不适用了,这里最好的解法就是用动态规划了。
//递推式还是跟 Unique Paths 一样,只是每次我们要判断一下是不是障碍,如果是,则dp[i][j] = 0,
//否则还是dp[i][j] = dp[i - 1][j] + dp[i][j - 1]。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
if (m== 0 || n == 0)
return 0;
vector<int> dp(n);
dp[0] = 1;
for (int i = 0; i < obstacleGrid.size(); ++i)
{
for (int j = 0; j < obstacleGrid[0].size();++j)
{
if (obstacleGrid[i][j] == 1)
dp[j] = 0;
else
{
if (j>0) dp[j] = dp[j] + dp[j - 1];
}
}
}
return dp[n - 1];
}
};
下面还有一种更容易理解的方法:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int i, j, m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector<vector<int> > dp(m, vector<int>(n, 1));
if (obstacleGrid[m - 1][n - 1] == 1 || obstacleGrid[0][0] == 1) {
return 0;
}
//初始化动态规划矩阵dp
for (i = 0; i < m; i++)
{
if (obstacleGrid[i][0] == 0)
dp[i][0] = 1;
else
break;
}
while (i < m) //某一行有障碍物,则后面所有行都为0
{
dp[i][0] = 0;
i++;
}
for (j = 0; j <n; j++)
{
if (obstacleGrid[0][j] == 0)
dp[0][j] = 1;
else
break;
}
while (j < n) //某一列有障碍物,则后面所以列都为0
{
dp[0][j] = 0;
j++;
}
//动态规划核心代码
for (i = 1; i < m; i++)
{
for (j = 1; j < n; j++)
{
if (obstacleGrid[i][j] == 1)
dp[i][j] = 0;
else
dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
}
}
return dp[m - 1][n - 1];
}
};