zoukankan      html  css  js  c++  java
  • 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 中,使用动态规划,当前位置p[i][j]总路径数=p[i-1][j]+p[i][j-1],而初始条件就是p[i][0]=1,p[0][j]=1。因为此时的上和左边界只有一条路可以到达。

    回归本题,这一题设置了障碍,在障碍数组中为1 的地方是不能到达的。这里我们只需要修改unique paths的代码,加上一些限制条件就行。首先对初始化加条件,比如在左边界,当前位置的路径数p[i][0],如果此位置的障碍为0,则p[i][0]=p[i-1][0],障碍为1,则p[i][0]=0。这样又得单独考虑i=0且j=0的情况。上边界也是这样考虑。

    而对于非边界的情况,只要当前位置的障碍为1,则当前位置的路径数设为0,否则就是上面条件p[i][j]总路径数=p[i-1][j]+p[i][j-1]

    class Solution {
        public int uniquePathsWithObstacles(int[][] obstacleGrid) {
            int m=obstacleGrid.length;  //行数
            int n=obstacleGrid[0].length;//列数
            int[][] tmp=new int[m][n];
           
            for(int i=0;i<m;i++)
                for(int j=0;j<n;j++){
                    if(i==0&&j==0&&obstacleGrid[i][j]==0)
                        tmp[i][j]=1;
                    else if(i==0){
                        if(obstacleGrid[i][j]==0)
                            tmp[i][j]=tmp[i][j-1];
                        else
                            tmp[i][j]=0;
                    }else if(j==0){//左边界
                        if(obstacleGrid[i][j]==0)
                            tmp[i][j]=tmp[i-1][j];
                        else
                            tmp[i][j]=0;
                    }else{//非左上边界
                        if(obstacleGrid[i][j]==0)
                        tmp[i][j]=tmp[i-1][j]+tmp[i][j-1];
                    }
                }
            
            return tmp[m-1][n-1];
        }
    }
  • 相关阅读:
    SQL 通配符
    SQL 中定义别名
    SQL 语句执行顺序
    将汉字散列存储
    FileStream写文本文档时候显示其他进程正在访问的问题
    向数据库中添加含有单引号的数据
    整词二分、逐字二分的分词词典机制
    C# 集合类总结(Array,Arraylist,List,Hashtable,Dictionary,Stack,Queue)
    固定表格宽度
    对于交叉表的实现及多重表头的应用
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8183783.html
Copyright © 2011-2022 走看看