File tree 1 file changed +22
-25
lines changed
solution/0000-0099/0063.Unique Paths II
1 file changed +22
-25
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public int uniquePathsWithObstacles (int [][] obstacleGrid ) {
3
- int n = obstacleGrid .length ;
4
- int m = obstacleGrid [0 ].length ;
5
- int [][] res = new int [n ][m ];
6
- int i = 0 ;
7
- while (i < n && obstacleGrid [i ][0 ] == 0 ) {
8
- // 无障碍物
9
- res [i ++][0 ] = 1 ;
10
- }
11
- while (i < n ) {
12
- res [i ++][0 ] = 0 ;
13
- }
14
-
15
- i = 0 ;
16
- while (i < m && obstacleGrid [0 ][i ] == 0 ) {
17
- // 无障碍物
18
- res [0 ][i ++] = 1 ;
3
+ int column = obstacleGrid [0 ].length , row = obstacleGrid .length ;
4
+ int [][] dp = new int [row ][column ];
5
+ // 第一行
6
+ for (int i = 0 ; i < column ; i ++) {
7
+ if (obstacleGrid [0 ][i ] == 1 ) {
8
+ break ;
9
+ }
10
+ dp [0 ][i ] = 1 ;
19
11
}
20
- while (i < m ) {
21
- res [0 ][i ++] = 0 ;
12
+
13
+ // 第一列
14
+ for (int i = 0 ; i < row ; i ++) {
15
+ if (obstacleGrid [i ][0 ] == 1 ) {
16
+ break ;
17
+ }
18
+ dp [i ][0 ] = 1 ;
22
19
}
23
-
24
- for (int k = 1 ; k < n ; ++k ) {
25
- for (int j = 1 ; j < m ; ++j ) {
26
- res [k ][j ] = obstacleGrid [k ][j ] == 1 ? 0 : (res [k - 1 ][j ] + res [k ][j - 1 ]);
20
+
21
+ // dp
22
+ for (int i = 1 ; i < row ; i ++) {
23
+ for (int j = 1 ; j < column ; j ++) {
24
+ dp [i ][j ] = obstacleGrid [i ][j ] == 1 ? 0 : dp [i - 1 ][j ] + dp [i ][j - 1 ];
27
25
}
28
26
}
29
-
30
- return res [n - 1 ][m - 1 ];
31
-
27
+
28
+ return dp [row - 1 ][column - 1 ];
32
29
}
33
30
}
You can’t perform that action at this time.
0 commit comments