LeetCode | Unique Paths II(唯一路径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 3×3 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.

题目解析:

这道题是上一题的扩展:LeetCode | Unique Paths

注意的是先初始化第一行和第一列,从左到右初始化的过程中,碰到一个结点有障碍物,那么从该点开始之后的路径值都为0。

当遍历内部结点的时候,没有障碍物就是左边和上面两个路径值的和。不用刻意判断左边和上面是否有障碍物,有的话路径值已经赋为0了,直接相加即可。

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
        vector<vector<int> >res;
        int row = obstacleGrid.size();
        if(row == 0)
            return 0;
        int col = obstacleGrid[0].size();
        if(col == 0)
            return 0;
        for(int i = 0;i < row;i++){
            vector<int> tmp = vector<int> (col,0);
            res.push_back(tmp);
        }
        //一开始就有阻碍物的话,就一定不可达
        if(obstacleGrid[0][0] == 1)
            return 0;
        //初始化,第一行和第一列,当碰到有一个障碍物的时候,后面的或下面的就全为0
        for(int i = 0;i < row;i++){
            if(obstacleGrid[i][0] == 0){
                res[i][0] = 1;
            }else
                break;
        }
        for(int j = 0;j < col;j++){
            if(obstacleGrid[0][j] == 0)
                res[0][j] = 1;
            else
                break;
        }
        //如果这个位置没有障碍物,那么其路径为右边过来的和上面过来的之和,
        //如果有障碍物就为0,因为已经初始化了,就不用赋值了
        for(int i = 1;i < row;i++){
            for(int j = 1;j < col;j++){
                if(obstacleGrid[i][j] == 0)
                    res[i][j] = res[i-1][j] + res[i][j-1];
            }
        }
        return res[row-1][col-1];
    }
};

点赞