Advertisement
Guest User

Untitled

a guest
Aug 16th, 2021
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.09 KB | None | 0 0
  1. class Solution {
  2.   public int uniquePathsWithObstacles(int[][] grid) {        
  3.     int R = grid.length;
  4.     int C = grid[0].length;
  5.    
  6.     if (R == 0 || C == 0) return 0;
  7.    
  8.     // if first column has obstacle, no path to destination
  9.     if (grid[0][0] == 1) return 0;
  10.    
  11.     grid[0][0] = 1;
  12.    
  13.     // if cell in first row contains obstacle,
  14.     // set 0 to that cell and all cell after.
  15.     for (int col = 1; col < C; col++) {
  16.       grid[0][col] = grid[0][col] == 1 ? 0 : grid[0][col - 1];      
  17.     }
  18.    
  19.     // if cell in first column contians obstacle,
  20.     // set 0 to that cell and all cell after.
  21.     for (int row = 1; row < R; row++) {
  22.       grid[row][0] = grid[row][0] == 1 ? 0 : grid[row - 1][0];
  23.     }
  24.    
  25.     for (int row = 1; row < R; row++) {
  26.       for (int col = 1; col < C; col++) {              
  27.         if (grid[row][col] == 1) {
  28.           // set 0 to cell is obstacle
  29.           grid[row][col] = 0;
  30.         } else {
  31.           grid[row][col] = grid[row - 1][col] + grid[row][col - 1];
  32.         }
  33.       }
  34.     }
  35.    
  36.     return grid[R - 1][C - 1];
  37.   }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement