File tree Expand file tree Collapse file tree 2 files changed +56
-0
lines changed
Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ Follow up for "Unique Paths":
2+
3+ Now consider if some obstacles are added to the grids. How many unique paths would there be?
4+
5+ An obstacle and empty space is marked as ` 1 ` and ` 0 ` respectively in the grid.
6+
7+ For example,
8+ There is one obstacle in the middle of a 3x3 grid as illustrated below.
9+ ```
10+ [
11+ [0,0,0],
12+ [0,1,0],
13+ [0,0,0]
14+ ]
15+ ```
16+ The total number of unique paths is ` 2 ` .
17+
18+ ** Note:** * m* and * n* will be at most 100.
Original file line number Diff line number Diff line change 1+ public class Solution {
2+ public int uniquePathsWithObstacles (int [][] obstacleGrid ) {
3+ if (obstacleGrid == null || obstacleGrid .length == 0
4+ || obstacleGrid [0 ].length == 0 || obstacleGrid [0 ][0 ] == 1 )
5+ return 0 ;
6+
7+ int m = obstacleGrid .length ;
8+ int n = obstacleGrid [0 ].length ;
9+
10+ int [][] result = new int [m ][n ];
11+ result [0 ][0 ] = 1 ;
12+
13+ for (int i = 1 ; i < m ; i ++) {
14+ if (obstacleGrid [i ][0 ] == 1 )
15+ break ;
16+
17+ result [i ][0 ] = 1 ;
18+ }
19+
20+ for (int i = 1 ; i < n ; i ++) {
21+ if (obstacleGrid [0 ][i ] == 1 )
22+ break ;
23+
24+ result [0 ][i ] = 1 ;
25+ }
26+
27+ for (int i = 1 ; i < m ; i ++) {
28+ for (int j = 1 ; j < n ; j ++) {
29+ if (obstacleGrid [i ][j ] == 1 )
30+ result [i ][j ] = 0 ;
31+ else
32+ result [i ][j ] = result [i -1 ][j ] + result [i ][j -1 ];
33+ }
34+ }
35+
36+ return result [m -1 ][n -1 ];
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments