63. Unique Paths II 找唯一途径2(中间有路障)

来源:互联网 发布:linux svn服务端搭建 编辑:程序博客网 时间:2024/06/06 02:23

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.


1.我的解答

还是在上一题的基础上,仍用一列矩阵来存路径,只不过若有路障,就把这个位置的路径设为1,其余不变。

注意:在只有一行或只有一列时,若有路障,则直接输出0;

在滚动数组时,对第0列和第0行的赋值要注意。对第0列,若有路障,则下面的值都为0;对第0行,若前面的为路障,则后面的都为0,否则为1(1是从开始到该位置的路径只有1)

class Solution {public:    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {        int row = obstacleGrid.size();        int col = obstacleGrid[0].size();        if(row==1 || col == 1){        if(row == 1){            for(int k = 0; k < col; k++)            if(obstacleGrid[0][k] == 1)            return 0;        }        if(col == 1){            for(int k = 0; k < row; k++)            if(obstacleGrid[k][0] == 1)            return 0;        }        return 1;        }                vector<int>vec(row,1);        for(int i = 0; i < col; i++)        for(int j = 0; j < row; j++){            if(obstacleGrid[j][i] == 1){                vec[j] = 0;                }else{                    if(j == 0){                         if(i>=1 && vec[j] == 0)                            vec[j] = 0;                        else                            vec[j] = 1;                    }                    else{                        if(i == 0)                            vec[j] = vec[j-1];                        else                            vec[j] += vec[j-1];                    }                }        }        return vec[row-1];    }};


0 0