# Leetcode 63:Unique Paths II

Datetime:2016-08-23 01:21:26         Topic: LeetCode          Share        Original >>

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` .

Note: m and  n will be at most 100.

Subscribe to see which companies asked this question

```//这道题跟 Unique Paths 差不多，只是这道题给机器人加了障碍，不是每次都有两个选择（向右，向下）了。
//因为有了这个条件，所以 Unique Paths 中最后一个直接求组合的方法就不适用了，这里最好的解法就是用动态规划了。
//递推式还是跟 Unique Paths 一样，只是每次我们要判断一下是不是障碍，如果是，则dp[i][j] = 0，
//否则还是dp[i][j] = dp[i - 1][j] + dp[i][j - 1]。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
if (m== 0 || n == 0)
return 0;

vector<int> dp(n);
dp[0] = 1;
for (int i = 0; i < obstacleGrid.size(); ++i)
{
for (int j = 0; j < obstacleGrid[0].size();++j)
{
if (obstacleGrid[i][j] == 1)
dp[j] = 0;
else
{
if (j>0)   dp[j] = dp[j] + dp[j - 1];
}
}
}
return dp[n - 1];
}
};```