JAVA solution, modified form uniquePath I


  • 3
    L

    modified form uniquePath I;
    set the upper and left boundary of the answer matrix to 1 until blocked;
    set any blocks to 0

    public class Solution {
        public int uniquePathsWithObstacles(int[][] obstacleGrid) {
            int width = obstacleGrid[0].length;
            int lines = obstacleGrid.length;
            int [][] answer = new int[lines][width];
            
           
            
            for(int j=0;j<width;j++){
                if(obstacleGrid[0][j]==1){if(lines==1) return 0; break;}
                else answer[0][j]=1;
            }
            
            for(int i=0;i<lines;i++){
                if(obstacleGrid[i][0]==1){if(width==1) return 0; break;}
                else answer[i][0]=1;
            }
            
            for(int i=1;i<lines;i++){
                for(int j=1;j<width;j++){
                    if(obstacleGrid[i][j]!=1){
                        answer[i][j]=answer[i-1][j]+answer[i][j-1];
                    }
                }
            }
            
            return answer[lines-1][width-1];
            
        }
    }

Log in to reply
 

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