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

#### leetcode63解题报告

2016-03-02 21:00:18

#### LeetCode 63

2016-06-09 18:27:06

#### LeetCode（63）Unique Paths II

2015-09-11 21:24:37

#### LeetCode63:Unique Paths II

2015-06-12 16:05:00

#### LeetCode cpp最新中文题解.pdf

2018年01月10日 866KB 下载

#### [LeetCode]63 不同的路径总数之二

2016-02-28 13:42:33

#### LeetCode(63)UniquePath2

2014-03-05 02:54:10

#### [C++]LeetCode: 63 Subsets

2014-12-30 21:13:48

#### Leetcode 63. Unique Paths II (Medium) (java)

2016-10-09 23:49:10

#### 【leetcode】63. Unique Paths II【java】

2016-12-17 13:37:05

## 不良信息举报

leetcode #63 in cpp