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];
        }
    };
  • 相关阅读:
    js- 类数组对象
    js- caller、 callee
    ES6 声明变量的6种方法
    Vue 之 element-ui upload组件的文件类型
    js中call、apply和bind的区别
    Vue 之 Vue.nextTick()
    DocumentFragment --更快捷操作DOM的途径
    Js 编程题汇总
    &#65279
    网站添加变量后变成空白
  • 原文地址:https://www.cnblogs.com/zhoudayang/p/5013398.html
Copyright © 2011-2022 走看看