-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path63. Unique Path II
66 lines (58 loc) · 2.13 KB
/
63. Unique Path II
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
// int m = obstacleGrid.length;
// int n = obstacleGrid[0].length;
// // use dp
// Integer[][] map = new Integer[m][n];
// if(obstacleGrid[0][0] == 1){
// return 0;
// }else{
// map[0][0] = 1;
// }
// for(int i = 1; i<m;i++){
// if(map[i-1][0] != 0){
// map[i][0] = 1;
// }
// if(obstacleGrid[i][0] == 1){
// map[i][0] = 0;
// }
// }
// for(int j= 1;j<n;j++){
// if(map[0][j-1] != 0){
// map[0][j] = 1;
// }
// if(obstacleGrid[0][j] == 1){
// map[0][j] = 0;
// }
// }
// for(int i = 1;i < m;i++){
// for(int j = 1; j < n;j++){
// if(i != 0 && j!= 0)
// map[i][j] = map[i-1][j] + map[i][j-1];
// if(obstacleGrid[i][j] == 1){
// map[i][j] = 0;
// }
// }
// }
// return map[m-1][n-1];
//Empty case
if(obstacleGrid.length == 0) return 0;
int rows = obstacleGrid.length;
int cols = obstacleGrid[0].length;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(obstacleGrid[i][j] == 1)
obstacleGrid[i][j] = 0;
else if(i == 0 && j == 0)
obstacleGrid[i][j] = 1;
else if(i == 0)
obstacleGrid[i][j] = obstacleGrid[i][j - 1] * 1;// For row 0, if there are no paths to left cell, then its 0,else 1
else if(j == 0)
obstacleGrid[i][j] = obstacleGrid[i - 1][j] * 1;// For col 0, if there are no paths to upper cell, then its 0,else 1
else
obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
}
}
return obstacleGrid[rows - 1][cols - 1];
}
}