63. Unique Paths II (2D-dp)

้€™้กŒ่ทŸ leetcode 62 ๅทฎๅˆฅไธป่ฆๅœจไธ่ƒฝๅˆๅง‹ๅŒ–ๆ‰€ๆœ‰dp ไธ€้–‹ๅง‹็‚บ 1 ไบ†, ๅ› ็‚บ้‡ๅˆฐ้šœ็ค™ๆ˜ฏไธ่ƒฝ่ตฐ็š„

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid != null && obstacleGrid.length == 0) return 0;
        
        int n = obstacleGrid[0].length;
        int dp[] = new int[n];
        dp[0] = 1; // ้ ่จญ่ตทๅง‹ 1
        for (int[] row : obstacleGrid) {
            for (int j = 0; j < n; j++) {
                if (row[j] == 1) { // row's col value, ้‡ๅˆฐ้šœ็ค™
                    dp[j] = 0; 
                } else if (j > 0) {
                    dp[j] += dp[j-1];
                }
            }
        }
        return dp[n-1];
    }
}

easy way to solve

time: O(m*n)

space:(m*n)

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        int dp[][] = new int[m][n];

        // if has obstacle, the following way will be 0
        // 1 1 1 obstacle 0 0 0 0 0
        for (int i = 0; i < m ; i++) {
            if (obstacleGrid[i][0] == 1) {
                break;
            }
            dp[i][0] = 1;
        }
        for (int j = 0; j < n ; j++) {
            if (obstacleGrid[0][j] == 1) {
                break;
            }
            dp[0][j] = 1;
        }
        
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] == 1) { // has obstacle, pass cal this time
                    continue;
                }
                dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m-1][n-1];
    }
}

/*
top down
if (obstacleGrid[i][j] == 1) {
    continue;
}

dp[i][j] = dp[i-1][j] + dp[i][j-1];
*/

Last updated