File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -118,4 +118,33 @@ public int uniquePathsWithObstaclesDP_Review(int[][] obstacleGrid) {
118
118
119
119
return dp [rows - 1 ][column - 1 ];
120
120
}
121
+
122
+ public int uniquePathsWithObstaclesDP_3rd (int [][] obstacleGrid ) {
123
+ int rows = obstacleGrid .length ;
124
+ int column = obstacleGrid [0 ].length ;
125
+ int [][] dp = new int [rows ][column ];
126
+ if (obstacleGrid [0 ][0 ] == 1 || obstacleGrid [rows - 1 ][column - 1 ] == 1 ) {
127
+ return 0 ;
128
+ } else {
129
+ dp [0 ][0 ] = 1 ;
130
+ }
131
+ for (int i = 1 ; i < rows ; i ++) {
132
+ if (obstacleGrid [i ][0 ] != 1 ) {
133
+ dp [i ][0 ] = dp [i - 1 ][0 ];
134
+ }
135
+ }
136
+ for (int j = 1 ; j < column ; j ++) {
137
+ if (obstacleGrid [j ][0 ] != 1 ) {
138
+ dp [0 ][j ] = dp [0 ][j - 1 ];
139
+ }
140
+ }
141
+ for (int i = 1 ; i < rows ; i ++) {
142
+ for (int j = 1 ; j < column ; j ++) {
143
+ if (obstacleGrid [i ][j ] != 1 ) {
144
+ dp [i ][j ] = dp [i - 1 ][j ] + dp [i ][j - 1 ];
145
+ }
146
+ }
147
+ }
148
+ return dp [rows - 1 ][column - 1 ];
149
+ }
121
150
}
Original file line number Diff line number Diff line change @@ -51,4 +51,21 @@ public void testUniquePathsWithObstaclesDP_Review() {
51
51
{{0 , 0 }, {1 , 1 }, {0 , 0 }}
52
52
), is (0 ));
53
53
}
54
+
55
+ @ Test
56
+ public void testUniquePathsWithObstaclesDP_3RD () {
57
+ assertThat (uniquePathsWithObstaclesDomain .uniquePathsWithObstaclesDP_3rd (new int [][]{
58
+ {0 , 0 , 0 },
59
+ {0 , 1 , 0 },
60
+ {0 , 0 , 0 }
61
+ }), is (2 ));
62
+
63
+ assertThat (uniquePathsWithObstaclesDomain .uniquePathsWithObstaclesDP_3rd (new int [][]{
64
+ {1 , 0 }
65
+ }), is (0 ));
66
+
67
+ assertThat (uniquePathsWithObstaclesDomain .uniquePathsWithObstaclesDP_3rd (new int [][]
68
+ {{0 , 0 }, {1 , 1 }, {0 , 0 }}
69
+ ), is (0 ));
70
+ }
54
71
}
You can’t perform that action at this time.
0 commit comments