• Unique Paths II ——LeetCode


    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.

    跟上一个题类似。

    题目大意:左上走到右下,1表示障碍,0表示路,问有多少种唯一的走法。

    解题思路:简单的动规,F(i,j)=F(i-1,j)+F(i,j-1),如果grid[i][j]==1,那么F(i,j)=0。

    public class Solution {
        public int uniquePathsWithObstacles(int[][] og) {
            if(og==null||og[0].length==0||og[0][0]==1){
                return 0;
            }
            int m = og.length,n=og[0].length;
            int[][] cnt = new int[m][n];
            cnt[0][0]=1;
            for(int i=0;i<m;i++){
                for(int j=0;j<n;j++){
                    if((i==0&&j==0)||og[i][j]==1){
                        continue;
                    } else if(i==0&&j!=0){
                        cnt[i][j]=cnt[i][j-1];
                    } else if(j==0&&i!=0){
                        cnt[i][j]=cnt[i-1][j];
                    } else {
                        cnt[i][j]=cnt[i-1][j]+cnt[i][j-1];
                    }
                }
            }
            return cnt[m-1][n-1];
        }
    }
  • 相关阅读:
    depth深度
    Springboot之异步任务和任务调度
    Spring + SpringMVC + MyBatis 整合
    SpringMVC 拦截器配置
    SpringMVC 简单入门
    MyBatis-Spring 事务配置
    MyBatis-Spring 简单入门
    Spring AOP
    Java 动态代理实现
    mongo 停止创建索引 --noIndexBuildRetry
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4599781.html
Copyright © 2020-2023  润新知