题目
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 3×3 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.
分析
与上一道题相比,此题增加了路径障碍这一条件,无障碍的点用0表示,有障碍的点用1表示。基本思路与上一道题相同,假设f(i, j)表示到达点(i, j)可走的路径数,那么在无障碍的情况下f(i, j)=f(i-1, j) + f(i, j-1)。如若有障碍,我们首先判断最左上角的起点是否为障碍点,如果其为障碍点,则路径数必为0。而当起点不是障碍点时,需考虑边界点的路径数,因为此时边界点和其左邻或上邻有关,因此若当前边界点非障碍点,f(i, 0)=f(i-1, 0)(左边界情况,上边界与之相似)。边界点赋值完毕,即可赋值非边界点,当然也要考虑当前点是否为障碍点的情况。 算法复杂度为O(m*n)。
解答
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m=obstacleGrid.size();
int n=obstacleGrid[0].size();
if(obstacleGrid[0][0]==1 || obstacleGrid[m-1][n-1]==1)
return 0;
vector<vector<int> > path(m,vector<int> (n,0));
if(obstacleGrid[0][0]==0){
path[0][0]=1;
}
for(int i=1;i<m;i++){
if(obstacleGrid[i][0]==0){
path[i][0]=path[i-1][0];
}
}
for(int j=1;j<n;j++){
if(obstacleGrid[0][j]==0){
path[0][j]=path[0][j-1];
}
}
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
if(obstacleGrid[i][j]==1){
path[i][j]=0;
}
else path[i][j]=path[i-1][j]+path[i][j-1];
}
}
return path[m-1][n-1];
}
};