zoukankan      html  css  js  c++  java
  • LeetCode-63.Unique Paths II

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

    The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

    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.

    Note: m and n will be at most 100.

    Example 1:

    Input:
    [
      [0,0,0],
      [0,1,0],
      [0,0,0]
    ]
    Output: 2
    Explanation:
    There is one obstacle in the middle of the 3x3 grid above.
    There are two ways to reach the bottom-right corner:
    1. Right -> Right -> Down -> Down
    2. Down -> Down -> Right -> Right

    使用dp,要判断当前位置是不是1,若是1则表示当前位置值为0,否则使用递推式计算;

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {//my dp
            //应该做判空处理,这里没有判断
            int m = obstacleGrid.length;
            int n = obstacleGrid[0].length;
            int[][] flag = new int[m+1][n+1]; 
            if(obstacleGrid[0][0]==1){//如果0 0 位置是1,则表示没有路径可达
                return 0;
            }
            for(int i = 1;i <= m;i++){
                for(int j = 1;j<=n;j++){
                    if(obstacleGrid[i-1][j-1]==1){
                        flag[i][j] = 0;
                    }
                    else{
                        if(1 == i && 1==j){
                            flag[i][j] =1;
                        }
                        else{
                            flag[i][j] = flag[i-1][j]+flag[i][j-1];
                        }                    
                    }
                    
                }
            }
            return flag[m][n];
        }

     相关题:

    不同的路径  LeetCode62   https://www.cnblogs.com/zhacai/p/10941798.html

  • 相关阅读:
    float对内联元素和块元素的影响
    行内元素的困扰
    Nodejs同步和异步编程
    let、const、var的区别
    作用域
    SpringMVC
    MVC2新闻编译与发布
    JSP显示新闻
    servlet应用
    SWPU邮件登录界面的仿写(第二次作业)
  • 原文地址:https://www.cnblogs.com/zhacai/p/10941829.html
Copyright © 2011-2022 走看看