首页 > 其他 > 详细

63. 不同路径 II

时间:2021-06-04 22:37:22      阅读:22      评论:0      收藏:0      [点我收藏+]
package leetcode;

public class demo_63 {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int[][] dp=new int[obstacleGrid.length][obstacleGrid[0].length];
        int flag=0;
        //如果初始位置就有障碍,则所有都不通过
        if(obstacleGrid[0][0]==1) {return 0;}
        for(int i=0;i<obstacleGrid.length;i++) {
            //如果最上边有一个障碍,则最上边障碍物之后的点都是不可达的
            for(int j=0;j<obstacleGrid[0].length;j++) {
                if(i==0&&obstacleGrid[i][j]==1) {
                    for(int w=j;w<obstacleGrid[0].length;w++) {
                        dp[i][w]=0;
                    }
                    break;
                }
                ////如果最左边有一个障碍,则最左边障碍物之后的点都是不可达的
                if(j==0&&obstacleGrid[i][j]==1) {
                    dp[i][j]=0;
                    flag=1;
                }
                if(j==0&&flag==1) {
                    dp[i][j]=0;
                    continue;
                }
                //动态规划
                if(i==0||j==0) {
                    dp[i][j]=1;
                }
                else {
                    if(obstacleGrid[i][j]==1) {
                        dp[i][j]=0;
                    }
                    else {
                        dp[i][j]=dp[i][j-1]+dp[i-1][j];
                    }
                }
            }
        }
        System.out.println(dp[obstacleGrid.length-1][obstacleGrid[0].length-1]);
        return dp[obstacleGrid.length-1][obstacleGrid[0].length-1];
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        demo_63 d63=new demo_63();
        int[][] obstacleGrid= {{0,1},{0,0}};
        d63.uniquePathsWithObstacles(obstacleGrid);
    }

}

 

63. 不同路径 II

原文:https://www.cnblogs.com/Yshun/p/14851362.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!