题目名称
63. Unique Paths II
描述
Follow up for “Unique Paths”:
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.
分析
与之前那个Unique Paths很类似,只是多了障碍物,这时候我们还是用一个二维向量来动态存储路径。与之前那个不同的是:我们先初始化一个m*n的值全部为0的二维向量,先对第一行和第一列遍历,如果没有遇到障碍物(obstacleGrid[i][j]==0),那么就把相应位置的path置为1,一旦碰到障碍物(obstacleGrid[i][j]!=0),表明此路不通,跳出循环。
后面的过程跟之前那个Unique Paths几乎一样,只是多了一个障碍物的判断,如果当前位置有障碍物,则路径值值为0,否则路径值等于该位置上方的路径值加上该位置左方的路径值。
C++代码
#include <iostream>
#include <vector>
using namespace std;
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if (m == 0 || n == 0 || obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1)
return 0;
vector<vector<int>> path(m, vector<int>(n, 0));
//因为在之前已经判断过起点和终点了,所以这里起点肯定没有障碍物
path[0][0] = 1;
//遍历obstacleGrid的第一行,设置path值
for (int j = 1; j < n; ++j) {
if (obstacleGrid[0][j] == 0)
path[0][j] = 1;
else
break;
}
//遍历obstacleGrid的第一列,设置path值
for (int i = 1; i < m; ++i) {
if (obstacleGrid[i][0] == 0)
path[i][0] = 1;
else
break;
}
//只有直到了第一行和第一列的path值,
//我们才能动态的得到剩下位置的path值
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
//当前位置有障碍物,path置为0
if (obstacleGrid[i][j] != 0)
path[i][j] = 0;
else
path[i][j] = path[i][j - 1] + path[i - 1][j];
}
}
return path[m - 1][n - 1];
}
int main() {
int m = 4, n = 6;
vector<int> a = { 0,0 };
vector<int> b = { 1,1 };
vector<int> c = { 0,0 };
vector<vector<int>> data;
data.push_back(a);
data.push_back(b);
data.push_back(c);
int res = uniquePathsWithObstacles(data);
cout << res << endl;
system("PAUSE");
return 0;
}
总结
加了约束条件的路径值求解,动态规划简单题目。