-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCode12DifferPaths01.java
More file actions
99 lines (82 loc) · 3.29 KB
/
Code12DifferPaths01.java
File metadata and controls
99 lines (82 loc) · 3.29 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.leecode.Dynamicprogramming;
public class Code12DifferPaths01 {
// public int uniquePathsWithObstacles(int [][]obstacleGrid) {
// int m=obstacleGrid.length;
// int n=obstacleGrid[0].length;
// if (obstacleGrid[0][0]==1) return 0;
// for (int i=0; i < m; i++) {
// if(obstacleGrid[0][i]==0){
// obstacleGrid[0][i]=1;
// }else{
// for(int j=i;j<m;j++){
// obstacleGrid[0][j]=0;
// }
// }
// }
//
// for(int i=1;i<n;i++){
// if(obstacleGrid[i][0]==0){
// obstacleGrid[i][0]=1;
// }else{
// for(int j=i;j<n;j++){
// obstacleGrid[0][j]=0;
// }
// }
// }
//
// for (int i = 1; i < m; i++) {
// for (int j = 1; j < n; j++) {
// if (obstacleGrid[i][j]!=1){
// obstacleGrid[i][j]=obstacleGrid[i][j-1]+obstacleGrid[i-1][j];
// }else{
// obstacleGrid[i][j]=0;
// }
// }
// }
// return obstacleGrid[m - 1][n - 1];
// }
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int R = obstacleGrid.length;
int C = obstacleGrid[0].length;
// If the starting cell has an obstacle, then simply return as there would be
// no paths to the destination.
if (obstacleGrid[0][0] == 1) {
return 0;
}
// Number of ways of reaching the starting cell = 1.
obstacleGrid[0][0] = 1;
// Filling the values for the first column
for (int i = 1; i < R; i++) {
obstacleGrid[i][0] = (obstacleGrid[i][0] == 0 && obstacleGrid[i - 1][0] == 1) ? 1 : 0;
}
// Filling the values for the first row
for (int i = 1; i < C; i++) {
obstacleGrid[0][i] = (obstacleGrid[0][i] == 0 && obstacleGrid[0][i - 1] == 1) ? 1 : 0;
}
// Starting from cell(1,1) fill up the values
// No. of ways of reaching cell[i][j] = cell[i - 1][j] + cell[i][j - 1]
// i.e. From above and left.
for (int i = 1; i < R; i++) {
for (int j = 1; j < C; j++) {
if (obstacleGrid[i][j] == 0) {
obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
} else {
obstacleGrid[i][j] = 0;
}
}
}
// Return value stored in rightmost bottommost cell. That is the destination.
return obstacleGrid[R - 1][C - 1];
}
public static void main(String[] args) {
int obstacleGrid[][]={{0,0,1},{0,0,0},{0,1,0}};
Code12DifferPaths01 code=new Code12DifferPaths01();
System.out.println(code.uniquePathsWithObstacles(obstacleGrid));
System.out.println("***************************");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.println(obstacleGrid[i][j]);
}
}
}
}