![这里写图片描述](https://img-blog.csdn.net/20180108232213721)
前面做过一道Unique Paths的题,那就顺便把Unique Paths II做了吧。这道题的要求基本和前面相同,从左上角出发,只能向左或者向右,求最终到达右下角有多少条路径,区别是这题多了障碍点,就是矩阵上数值为1的地方,有障碍的地方无法通行。
为了求解这道题,采取和之前类似的做法,先确定第一行和第一列的路径数,如果没遇到障碍那就全是1,如果有障碍,那么从障碍开始全是0。求出第一行和第一列的路径数之后,从左到右从上到下,求其他点的路径数,如果原先它在矩阵上的值是1,那么它的路径数为0。最终得到起点到终点的路径数。
代码如下:
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if (m == 0||n == 0) return 0;
bool firstObstacle = false;
bool hasObstacleFront = false;
if (obstacleGrid[0][0] == 1) firstObstacle = true;
for (int i = 0; i < n; i++) {
if (obstacleGrid[0][i] == 1) {
hasObstacleFront = true;
}
if (hasObstacleFront) {
for (int j = i; j < n; j++) {
obstacleGrid[0][j] = 0;
}
break;
} else {
obstacleGrid[0][i] = 1;
}
}
hasObstacleFront = firstObstacle;
for (int i = 1; i < m; i++) {
if (obstacleGrid[i][0] == 1) {
hasObstacleFront = true;
}
if (hasObstacleFront) {
for (int j = i; j < m; j++) {
obstacleGrid[j][0] = 0;
}
break;
} else {
obstacleGrid[i][0] = 1;
}
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (obstacleGrid[i][j]) {
obstacleGrid[i][j] = 0;
} else {
obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
}
}
}
return obstacleGrid[m - 1][n - 1];
}
};