63. Unique Paths II

# Medium

Solution:

  1. Initialize first row and first column of paths

  2. compute other elements of paths

Python example:

class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length, n = obstacleGrid[0].length;
        int[][] paths = new int[m][n];
        if(obstacleGrid[0][0] == 1)
            paths[0][0] = 0;
        else
            paths[0][0] = 1;
        
        for(int i = 1; i < m; i ++) {
            if(obstacleGrid[i][0] == 1)
                paths[i][0] = 0;
            else
                paths[i][0] = paths[i-1][0];
        }
        for(int j = 1; j < n; j ++) {
            if(obstacleGrid[0][j] == 1)
                paths[0][j] = 0;
            else
                paths[0][j] = paths[0][j-1];
        }
        
        for(int row = 1; row < m; row ++)
            for(int col = 1; col < n; col ++) {
                if(obstacleGrid[row][col] == 1)
                    paths[row][col] = 0;
                else
                    paths[row][col] = paths[row-1][col] + paths[row][col-1];
            }
        
        return paths[m-1][n-1];
    }
}

Last updated

Was this helpful?