# 不同路径 II
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?
网格中的障碍物和空位置分别用 1
和 0
来表示。
示例 1:
输入:obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
输出:2
解释:3x3 网格的正中间有一个障碍物。从左上角到右下角一共有 2 条不同的路径:
1. 向右 -> 向右 -> 向下 -> 向下
2. 向下 -> 向下 -> 向右 -> 向右
示例 2:
输入:obstacleGrid = [[0,1],[0,0]]
输出:1
提示:
m == obstacleGrid.length
n == obstacleGrid[i].length
1 <= m, n <= 100
obstacleGrid[i][j]
为 0
或 1
以下错误的选项是?
## aop
### before
```c
#include
using namespace std;
```
### after
```c
int main()
{
Solution sol;
int a = 2;
int b = 4;
vector> obstacleGrid = vector>(a, vector(b)) = {{0, 0, 0, 0}, {0, 1, 2, 3}};
int res;
res = sol.uniquePathsWithObstacles(obstacleGrid);
cout << res;
return 0;
}
```
## 答案
```c
class Solution
{
public:
int dp[110];
int uniquePathsWithObstacles(vector> &obstacleGrid)
{
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
if (obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1)
return 0;
dp[1] = 1;
for (int i = 1; i <= m; ++i)
{
for (int j = 1; j <= n; ++j)
{
if (obstacleGrid[i - 1][j - 1] == 0)
dp[j] += dp[j - 1];
else
dp[j] = 0;
}
}
return dp[n];
}
};
```
## 选项
### A
```c
class Solution
{
public:
int uniquePathsWithObstacles(vector> &obstacleGrid)
{
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector> dp(m, vector(n, 0));
for (int i = 0; i < m && obstacleGrid[i][0] != 1; i++)
{
dp[i][0] = 1;
}
for (int i = 0; i < n && obstacleGrid[0][i] != 1; i++)
{
dp[0][i] = 1;
}
for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; j++)
{
if (obstacleGrid[i][j] != 1)
{
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
return dp[m - 1][n - 1];
}
};
```
### B
```c
class Solution
{
public:
int uniquePathsWithObstacles(vector> &obstacleGrid)
{
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
int p[m][n];
int k = 0;
while (k < m && obstacleGrid[k][0] != 1)
p[k++][0] = 1;
while (k < m)
p[k++][0] = 0;
k = 0;
while (k < n && obstacleGrid[0][k] != 1)
p[0][k++] = 1;
while (k < n)
p[0][k++] = 0;
for (int i = 1; i < m; i++)
for (int j = 1; j < n; j++)
{
if (obstacleGrid[i][j] == 1)
p[i][j] = 0;
else
p[i][j] = p[i - 1][j] + p[i][j - 1];
}
return p[m - 1][n - 1];
}
};
```
### C
```c
class Solution
{
public:
int uniquePathsWithObstacles(vector> &obstacleGrid)
{
if (obstacleGrid.size() == 0 || obstacleGrid[0].size() == 0)
return 0;
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector> info(m, vector(n, 0));
for (int i = 0; i < m; ++i)
{
if (obstacleGrid[i][0] == 1)
{
for (int j = i; j < m; j++)
{
info[j][0] = 0;
}
break;
}
else
info[i][0] = 1;
}
for (int i = 0; i < n; ++i)
{
if (obstacleGrid[0][i] == 1)
{
for (int j = i; j < n; ++j)
{
info[0][j] = 0;
}
break;
}
else
info[0][i] = 1;
}
for (int i = 1; i < m; ++i)
{
for (int j = 1; j < n; ++j)
{
if (obstacleGrid[i][j] == 1)
{
info[i][j] = 0;
}
else
{
info[i][j] = info[i - 1][j] + info[i][j - 1];
}
}
}
return info[m - 1][n - 1];
}
};
```