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.

Note: m and n will be at most 100.

题意:和Unique Paths 类似 只是多了个障碍的限制

思想:那么我们可以想办法把这题转化成 Unique Paths 来做

           先判断第一列和第一行 如果位置为0 就把它标记为1 如果为1之后的位置全标记为0 因为都不可达

   再来判断其它的位置,如果该位置是障碍为1时 就标记为0(能到达的路径为0) 如果为0时那么就按照Unique Paths的思想 标记为path[i-1][j]+path[i][j-1];

AC代码:时间O(n*m) 空间O(n*m)

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        //1代表该位置能到达的一条路径 0表示0条路径
        ///判断第一列 如果该位置为0 就标记1 如果该位置为1 那么该位置以及后面位置全为0
        int flagx = 1;
        for(int i =0;i<m;i++)
            if(obstacleGrid[i][0]==0&&flagx)
                obstacleGrid[i][0] = 1;
            else{
                obstacleGrid[i][0] = 0;
                flagx=0;
                }
        ///判断第一行 如果该位置为0 就标记1 如果该位置为1 那么该位置以及后面位置全为0
        int flagy = 1;
        obstacleGrid[0][0] ^=1; //obstacleGrid[0][0] 起始位置 取原始值 再判断这一行每一位置的路径数
        for(int i =0;i<n;i++)
            if(obstacleGrid[0][i]==0&&flagy)
                obstacleGrid[0][i] = 1;
            else{
                obstacleGrid[0][i] = 0;
                flagy=0;
                }
        //和Unique Paths的思想一样 这里遍历的位置为1代表有障碍 不可达 所以设置可达路径为0
        for(int i=1;i<m;i++){
            for(int j=1;j<n;j++){
                if(obstacleGrid[i][j]==0){
                    obstacleGrid[i][j] = obstacleGrid[i-1][j]+obstacleGrid[i][j-1];
                }else{
                    obstacleGrid[i][j] = 0;
                }
            }
        }
        return obstacleGrid[m-1][n-1];
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值