# leetcode #63 in cpp

56人阅读 评论(0)

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];
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：7884次
• 积分：1394
• 等级：
• 排名：千里之外
• 原创：139篇
• 转载：0篇
• 译文：0篇
• 评论：0条
文章分类
文章存档
阅读排行
评论排行