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