Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int uniquePathsWithObstacles(int[][] grid) {
- int R = grid.length;
- int C = grid[0].length;
- if (R == 0 || C == 0) return 0;
- // if first column has obstacle, no path to destination
- if (grid[0][0] == 1) return 0;
- grid[0][0] = 1;
- // if cell in first row contains obstacle,
- // set 0 to that cell and all cell after.
- for (int col = 1; col < C; col++) {
- grid[0][col] = grid[0][col] == 1 ? 0 : grid[0][col - 1];
- }
- // if cell in first column contians obstacle,
- // set 0 to that cell and all cell after.
- for (int row = 1; row < R; row++) {
- grid[row][0] = grid[row][0] == 1 ? 0 : grid[row - 1][0];
- }
- for (int row = 1; row < R; row++) {
- for (int col = 1; col < C; col++) {
- if (grid[row][col] == 1) {
- // set 0 to cell is obstacle
- grid[row][col] = 0;
- } else {
- grid[row][col] = grid[row - 1][col] + grid[row][col - 1];
- }
- }
- }
- return grid[R - 1][C - 1];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement