美文网首页
UniquePaths_2_63

UniquePaths_2_63

作者: 7ccc099f4608 | 来源:发表于2020-02-28 13:56 被阅读0次

    https://leetcode-cn.com/problems/unique-paths-ii/

    image.png

    (图片来源https://leetcode-cn.com/problems/unique-paths-ii/

    日期 是否一次通过 comment
    2020-02-28 0 忘了处理grid边缘有1的情况

    初始化;交换;排障

    1. row 向
       public int uniquePathsWithObstacles1(int[][] obstacleGrid) {
            int rowL = obstacleGrid.length;
            int colL = obstacleGrid[0].length;
    
            int[] dp = new int[rowL];
            // 初始化
            for(int i=0; i<rowL; i++) {
                if(obstacleGrid[i][0] != 0) {
                    dp[i] = 0;
                    break;
                }
    
                dp[i] = 1;
            }
    
            // 遍历grid
            for (int j=1; j<colL; j++) {
                if(obstacleGrid[0][j] != 0) {  // grid边缘处理
                    dp[0] = 0;
                }
                for (int i=1; i < rowL; i++) {
                    if (obstacleGrid[i][j] != 0) {
                        dp[i] = 0;
                    } else { // j > 0 if (dp[i - 1] != 0)
                        dp[i] += dp[i - 1];
                    }
                }
            }
    
            return dp[rowL - 1];
        }
    
    1. col向
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
            int rowL = obstacleGrid.length;
            int colL = obstacleGrid[0].length;
    
            int[] dp = new int[colL];
            for(int j=0; j<colL; j++) {
                if(obstacleGrid[0][j] != 0) {
                    dp[j] = 0;
                    break;
                }
    
                dp[j] = 1;
            }
    
    
            for (int i=1; i<rowL; i++) {
                if(obstacleGrid[i][0] != 0) {
                    dp[0] = 0;
                }
                for (int j=1; j < colL; j++) {
                    if (obstacleGrid[i][j] != 0) {
                        dp[j] = 0;
                    } else { // j > 0
                        dp[j] += dp[j - 1];
                    }
                }
            }
    
            return dp[colL - 1];
        }
    

    相关文章

      网友评论

          本文标题:UniquePaths_2_63

          本文链接:https://www.haomeiwen.com/subject/qcqlhhtx.html