Advertisement
gelita

Unique Paths with obstacles Leetcode #63

Mar 10th, 2020
598
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.21 KB | None | 0 0
  1. class Solution {
  2.     public int uniquePathsWithObstacles(int[][] obstacleGrid) {
  3.         //check if null or blocked on step 1
  4.         if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0][0] == 1){
  5.             return 0;
  6.         }
  7.         int height = obstacleGrid.length;
  8.         int width = obstacleGrid[0].length;
  9.         int[][] paths = new int[height][width];
  10.         //set first row and col to 1 if no obstacle exists
  11.         for(int i=0; i<height; i++){
  12.             if(obstacleGrid[i][0] != 1){
  13.                 paths[i][0] = 1;
  14.             }else{
  15.                 break;
  16.             }
  17.         }
  18.         for(int j=0; j<width; j++){
  19.             if(obstacleGrid[0][j] != 1){
  20.                 paths[0][j] = 1;
  21.             }else{
  22.                 break;
  23.             }
  24.         }
  25.        
  26.         //for all other spaces on the grid
  27.         //start iterating at 1 since row 0 / col 0 is filled in already
  28.         for(int i = 1; i< height; i++){
  29.             for(int j =  1; j< width; j++){
  30.                 if(obstacleGrid[i][j] != 1){
  31.                     paths[i][j] = paths[i][j-1] + paths[i-1][j];
  32.                 }
  33.             }
  34.         }
  35.         return paths[height-1][width-1];
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement