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 as1and0respectively 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 is2.
Note: m and n will be at most 100.
题意:增加障碍,不能到达障碍,不能越过障碍。
思路:思路和unique paths是一样的,只是要判断当前值是否为1,若是,则其对应的dp数组中赋值为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[].size();
vector<vector<int>> dp(m,vector<int>(n,));
if(m==||n==) return ;
if(obstacleGrid[][]==) return ;
dp[][]=; //初始行
for(int i=;i<m;++i)
{
if(obstacleGrid[i][] ==)
{
break;
}
else
dp[i][]=;
}
//初始列
for(int i=;i<n;++i)
{
if(obstacleGrid[][i] ==)
{
break;
}
else
dp[][i]=;
} for(int i=;i<m;++i)
{
for(int j=;j<n;++j)
{
if(obstacleGrid[i][j] !=)
dp[i][j]=dp[i-][j]+dp[i][j-];
}
} return dp[m-][n-];
}
};
当用一维数组去简化时,要注意些问题,仅一行,或者仅一列时,还要依次的确定数组dp[]中对应的值,不是像上一题那样简单赋值为1就行,所以,遍历时,行和列的起始点都是从0开始;另外也得注意的是,数组dp中的当前的前一个是否存在,即, j >0。代码如下:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid)
{
int row=obstacleGrid.size(),col=obstacleGrid[].size();
if(obstacleGrid[][]==) return ;
vector<int> dp(col,);
dp[]=; for(int i=;i<row;++i)
{
for(int j=;j<col;++j)
{
if(obstacleGrid[i][j]==)
dp[j]=;
else if(j>)
dp[j]+=dp[j-];
}
}
return dp[col-];
}
};