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.
题意是: 给一个m*n的矩阵,矩阵的值为1,表示无法通过, 矩阵的值为0,表示可以通过,问从[0,0]到[m,n]一共有多少条独立的路径。
根据LeetCode62, 可以得出如果矩阵的值都为0,得到推导公式P[i,j]=P[i-1,j]+P[i,j-1], 当元素为1的时候,很明显该位置的P[i,j]=0,所以根据动态规划思想,可以得到如下的解法:
int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid)
{
int re=0;
if(obstacleGrid.size()==0||obstacleGrid[0][0]==1)
{
return re;
}
vector<int> path(obstacleGrid[0].size(),0);
path[0]=1;
for(int i=0;i<obstacleGrid.size();i++)
{
if(obstacleGrid[i][0]==1)
{
path[0]=0;
}
for(int j=1;j<path.size();j++)
{
if(obstacleGrid[i][j]==0)
{
path[j]+=path[j-1];
}
else {
path[j]=0;
}
}
}
re=path[path.size()-1];
return re;
}