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

    思路:

    同 LeetCode 62. Unique Paths, 只不过决定每个res[i][j]的时候,都要先判断:obstacleGrid[i][j]如果等于1,则res[i][j]=0; 否则正常进行。

    本题代码:

    import java.util.Scanner;
    
    /**
     * Created by yuanxu on 17/4/13.
     */
    public class DP63 {
    
        public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
            int m = obstacleGrid.length;
            int n = obstacleGrid[0].length;
            int res[][] = new int[m][n];// 数据从0开始
    
            // boundary condition
            res[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1;
            for (int i=1; i<m; i++) {
                if (res[i-1][0] == 0) {
                    res[i][0] = 0;
                } else if (obstacleGrid[i][0] == 1) {
                    res[i][0] = 0;
                } else {
                    res[i][0] = 1;
                }
            }
            for (int j=1; j<n; j++) {
                if (res[0][j-1] == 0) {
                    res[0][j-1] = 0;
                } else if (obstacleGrid[0][j] == 1) {
                    res[0][j] = 0;
                } else {
                    res[0][j] = 1;
                }
            }
    
            // DP
            for (int i=1; i<m; i++) {
                for (int j=1; j<n; j++) {
                    if (obstacleGrid[i][j] == 1) {
                        res[i][j] = 0;
                    } else {
                        res[i][j] = res[i-1][j] + res[i][j-1];
                    }
                }
            }
    
            return  res[m-1][n-1];
        }
    
    
        public  static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    //        int obstacleGrid[][] = {{0,0,0},{0,1,0},{0,0,0}};
    //        int obstacleGrid[][] = {{1}};
            int obstacleGrid[][] = {{0,0},{0,1}};
            System.out.println(uniquePathsWithObstacles(obstacleGrid));
        }
    }
  • 相关阅读:
    刷题86—动态规划(三)
    刷题85—动态规划(二)— 股票6道
    刷题84—动态规划(一)
    刷题83——硬币
    刷题82——二叉树的右视图
    刷题81——统计「优美子数组」
    android adb 流程原理代码分析(一)
    android默认开启adb调试方法分析
    recovery 下界面UI旋转90 180 270修改
    sublime使用Package Control不能正常使用的解决办法
  • 原文地址:https://www.cnblogs.com/pinganzi/p/6703033.html
Copyright © 2011-2022 走看看