-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetCodeQ63.java
More file actions
62 lines (53 loc) · 1.85 KB
/
leetCodeQ63.java
File metadata and controls
62 lines (53 loc) · 1.85 KB
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
package DynamicProgramming;
public class leetCodeQ63 {
// Memoization
public static int paths(int row, int col, int m, int n, int[][] arr) {
if (row >= m || col >= n)
return 0;
if (arr[row][col] == -1)
return 0;
if (row == m - 1 && col == n - 1)
return 1;
if (arr[row][col] != 0)
return arr[row][col];
int rightWays = paths(row, col + 1, m, n, arr);
int leftWays = paths(row + 1, col, m, n, arr);
return arr[row][col] = rightWays + leftWays;
}
// Tabulation
public static int uniquePathsWithObstacles(int[][] dp) {
int m = dp.length ;
int n = dp[0].length ;
for(int i = 0 ; i < m ; i++){
for(int j = 0 ; j < n ; j++){
if(dp[i][j] == 1)
dp[i][j] = 0 ;
else if(i == 0 && j == 0)
dp[i][j] = 1 ;
else{
int right = 0 , left = 0 ;
if(i > 0 )
right = dp[i-1][j] ;
if(j > 0 )
left = dp[i][j-1];
dp[i][j] = right + left ;
}
}
}
return dp[m-1][n-1] ;
}
public static void main(String[] args) {
int[][] obstacleGrid = { { 0, 0, 0 } , { 0, 1, 0 } , { 0, 0, 0 }} ;
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
System.out.println(uniquePathsWithObstacles(obstacleGrid));
int[][] obstacleGridT = {{0,0,0},{0,1,0},{0,0,0}} ;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (obstacleGridT[i][j] == 1)
obstacleGridT[i][j] = -1;
}
}
System.out.println(paths(0, 0, m, n, obstacleGridT));
}
}