# leetcode #63 in cpp

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.

Solution:

It is almost the same as #62. In this question we have to check if a position(i,j) has obstacle. If it has one, leave dp[i][j] as 0 as it has no paths to destination.

Code:

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if(obstacleGrid[m-1][n-1] == 1) return 0;//if destination has obstacle, it can never be reached
vector<vector<int>> dp(m, vector<int>(n,0));
dp[m-1][n-1] = 1;//set destination be 1
for(int i = m-2; i >=0 && n-1>=0; i --){//right border
if(obstacleGrid[i][n-1]!=1) dp[i][n-1] = dp[i+1][n-1];//if a position has obstacle, the cell above it would have path 0 to destination.
}
for(int i = n-2; i >=0 && m-1 >= 0; i--){//bottom row
if(obstacleGrid[m-1][i]!=1) dp[m-1][i] = dp[m-1][i+1];//if a position has obstacle, the cells at its left would have path 0 to destination.
}
for(int i = m-2; i >= 0; i --){
for(int j = n-2; j >= 0; j --){
//if it is obstacle, skip it and leave it as 0. There are no paths from obstacle to destination
//if not obstacle, then we could calculate the number of paths.
if(obstacleGrid[i][j] != 1) dp[i][j] += dp[i+1][j] + dp[i][j+1];
}
}
return dp[0][0];
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode #63 in cpp 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)