 # Untitled

a guest
Aug 16th, 2021
89
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. class Solution {
2.   public int uniquePathsWithObstacles(int[][] grid) {
3.     int R = grid.length;
4.     int C = grid.length;
5.
6.     if (R == 0 || C == 0) return 0;
7.
8.     // if first column has obstacle, no path to destination
9.     if (grid == 1) return 0;
10.
11.     grid = 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[col] = grid[col] == 1 ? 0 : grid[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] = grid[row] == 1 ? 0 : grid[row - 1];
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. }
RAW Paste Data