Java 1ms simple solution


  • 0
    public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        int[][] res = new int[m][n];
        if(obstacleGrid[0][0]==1||obstacleGrid[m-1][n-1]==1) return 0;
        //Get the result for grids on the top and left
        res[0][0] = 1;
        if(n>1){
            for(int j = 1;j<n;j++){
                if(obstacleGrid[0][j]==1||res[0][j-1]==0){
                    res[0][j] = 0;
                }
                else{
                    res[0][j] = 1;
                }
            }
        }
        if(m>1){
            for(int i = 1;i<m;i++){
                if(obstacleGrid[i][0]==1||res[i-1][0]==0){
                    res[i][0] = 0;
                }
                else{
                    res[i][0] = 1;
                }
            }
        }
        if(m==1)return res[0][n-1];
        if(n==1)return res[m-1][0];
        //Result for the rest grids
        for(int i = 1;i<m;i++){
            for(int j = 1;j<n;j++){
                if(obstacleGrid[i][j]==1){
                    res[i][j] = 0;
                    continue;
                }
                if(res[i-1][j]==0){
                    res[i][j] = res[i][j-1];
                }
                else if(res[i][j-1]==0){
                    res[i][j] = res[i-1][j];
                }
                else{
                    res[i][j] = res[i][j-1]+res[i-1][j];
                }
            }
        }
        return res[m-1][n-1];
    }
    }

  • 0

    Well, I did not solve it in place. In fact, the original array can be modified directly instead of using a new res array.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.