zoukankan      html  css  js  c++  java
  • 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.

     
    思路:整体思路和Unique Paths一致,就是当a[i][j]=1时,b[i][j]=0,而不是b[i-1][j]+b[i][j-1]。注意初始化a[i][0]和a[0][i]时,只要第一行或者第一列中出现了障碍物,那么就不可能再接着向右走与向下走了。所以要这样初始化:首先初始化b[0][0],如果a[0][0]=1,那么b[0][0]=0,否则为1。后面继续设置a[][]
    class Solution {
    private:
        int b[101][101];
    public:
        int uniquePathsWithObstacles(vector<vector<int>>& a) {
            int i,j;
            int row=a.size();
            int col=a[0].size();
            b[0][0]= a[0][0]==1? 0:1;
            for(i=1;i<row;i++)
                b[i][0]= a[i][0]==1? 0:b[i-1][0];
            for(i=1;i<col;i++)
                b[0][i]= a[0][i]==1? 0:b[0][i-1];
            for(i=1;i<row;i++){
                for(j=1;j<col;j++){
                    b[i][j]= a[i][j]==1?  0:b[i-1][j]+b[i][j-1];
                }
            }
            return b[row-1][col-1];
        }
    };
  • 相关阅读:
    Linux w命令
    01.drf文档及外键字段反序列化
    redis的参数解释
    redis集群复制和故障转移
    codis原理及部署_01
    redis 主从哨兵02
    redis 主从哨兵01
    redis持久化
    redis python操作
    redis cluster
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5013398.html
Copyright © 2011-2022 走看看