题目描述:
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
.
Note: m and n will be at most 100.
程序代码:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if (obstacleGrid.empty() || obstacleGrid[0].empty())
return 0;
// 得到高度、宽度m, n的值
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
// 建立一个二维数组
vector<int> temp(n, 0);
vector<vector<int> > f(m, temp);
// (0,0)处若无障碍,则此处路径数为1;若有障碍,则直接返回0
if (obstacleGrid[0][0] == 0) {
f[0][0] = 1;
}
else {
return 0;
}
// (i, j)处可到达路径数为其上或左处之和
// 注意处理边界处
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
continue;
}
if (obstacleGrid[i][j] == 0) {
if (i == 0) {
f[i][j] = f[i][j - 1];
}
else if (j == 0) {
f[i][j] = f[i - 1][j];
}
else {
f[i][j] = f[i - 1][j] + f[i][j - 1];
}
}
// 若该点处为障碍,则到达此点处路径数为0
else if (obstacleGrid[i][j] == 1) {
f[i][j] = 0;
}
}
}
return f[m - 1][n - 1];
}
};
简要题解:
本题运用了动态规划的算法。
先理清题意。本题是上周所做的前一题的延伸。需要从左上角的起点到右下角的终点,但中间可能遇到障碍物(障碍物表示为1,无障碍物则表示为0),求出总共可能的路径数量。
要解出本题,需要在本周所做的之前那题的基础上再考虑解决障碍物的问题。根据之前那题,我们已经可以列出无障碍物(即 obstacleGrid[i][j] == 0)时候该点处的转移方程:
if (i == 0) f[i][j] = f[i][j - 1]
else if ( j == 0) f[i][j] = f[i - 1][j]
else f[i][j] = f[i - 1][j] + f[i][j - 1]
接着要解决有障碍物时的问题。实际上解决方法很简单,当遇到障碍物时,即表示该点处不通(即 obstacleGrid[i][j] == 1),则走到此点处的可能路径数为0,所以对应转移方程:
f[i]j] = 0
这样就解决了这个延伸的问题。此外注意一下,起点处若 obstacleGrid值为1, 可直接输出结果为0. 最终的输出依然是f[m-1][n-1].
本题是本周所做上一题的延伸练习,增加了一个条件,让题目难度稍微增加。我感到,做这种相互关联的练习,有助于我更好地理解问题。