1
+ /*
2
+
3
+ Date: Dec 25, 2014
4
+ Problem: Unique Paths II
5
+ Difficulty: Easy
6
+ Source: https://oj.leetcode.com/problems/unique-paths-ii/
7
+ Notes:
8
+ Follow up for "Unique Paths":
9
+ Now consider if some obstacles are added to the grids. How many unique paths would there be?
10
+ An obstacle and empty space is marked as 1 and 0 respectively in the grid.
11
+ For example,
12
+ There is one obstacle in the middle of a 3x3 grid as illustrated below.
13
+ [
14
+ [0,0,0],
15
+ [0,1,0],
16
+ [0,0,0]
17
+ ]
18
+ The total number of unique paths is 2.
19
+ Note: m and n will be at most 100.
20
+
21
+ Solution: Dynamic programming.
22
+ */
23
+
24
+ public class Solution {
25
+ public int uniquePathsWithObstacles_1 (int [][] obstacleGrid ) {
26
+ int m = obstacleGrid .length ;
27
+ int n = obstacleGrid [0 ].length ;
28
+ int [][] dp = new int [m ][n ];
29
+ if (obstacleGrid [0 ][0 ] == 1 ) return 0 ;
30
+ dp [0 ][0 ] = 1 ;
31
+ for (int i = 1 ; i < m ; i ++)
32
+ dp [i ][0 ] = obstacleGrid [i ][0 ] == 1 ? 0 : dp [i -1 ][0 ];
33
+ for (int j = 1 ; j < n ; j ++)
34
+ dp [0 ][j ] = obstacleGrid [0 ][j ] == 1 ? 0 : dp [0 ][j -1 ];
35
+
36
+ for (int i = 1 ; i < m ; i ++)
37
+ for (int j = 1 ; j < n ; j ++)
38
+ dp [i ][j ] = obstacleGrid [i ][j ] == 1 ? 0 : dp [i -1 ][j ] + dp [i ][j -1 ];
39
+
40
+ return dp [m -1 ][n -1 ];
41
+ }
42
+ public int uniquePathsWithObstacles_2 (int [][] obstacleGrid ) {
43
+ int m = obstacleGrid .length ;
44
+ if (m == 0 ) return 0 ;
45
+ int n = obstacleGrid [0 ].length ;
46
+ int [] dp = new int [n ];
47
+ if (obstacleGrid [0 ][0 ] == 1 || obstacleGrid [m -1 ][n -1 ] == 1 ) return 0 ;
48
+ dp [0 ] = 1 ;
49
+ for (int i = 0 ; i < m ; ++i ) {
50
+ dp [0 ] = obstacleGrid [i ][0 ] == 1 ? 0 : dp [0 ];
51
+ for (int j = 1 ; j < n ; ++j ) {
52
+ dp [j ] = obstacleGrid [i ][j ] == 1 ? 0 : dp [j ] + dp [j -1 ];
53
+ }
54
+ }
55
+ return dp [n -1 ];
56
+ }
57
+ }
0 commit comments