Skip to content

Commit 8ee888d

Browse files
unique paths II
1 parent 2c80b43 commit 8ee888d

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

MEDIUM/src/medium/UniquePathsII.java

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package medium;
2+
3+
import utils.CommonUtils;
4+
5+
/**63. Unique Paths II QuestionEditorial Solution My Submissions
6+
Total Accepted: 72924
7+
Total Submissions: 243328
8+
Difficulty: Medium
9+
Follow up for "Unique Paths":
10+
11+
Now consider if some obstacles are added to the grids. How many unique paths would there be?
12+
13+
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
14+
15+
For example,
16+
There is one obstacle in the middle of a 3x3 grid as illustrated below.
17+
18+
[
19+
[0,0,0],
20+
[0,1,0],
21+
[0,0,0]
22+
]
23+
The total number of unique paths is 2.
24+
25+
Note: m and n will be at most 100.*/
26+
public class UniquePathsII {
27+
/**Idea: grid[i][j] has to be set to zero if obstacleGrid[i][j] == 1,
28+
* otherwise, we can get dp[i][j] from its top and left dp.*/
29+
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
30+
if(obstacleGrid == null || obstacleGrid.length == 0) return 0;
31+
32+
int height = obstacleGrid.length, width = obstacleGrid[0].length;
33+
int[][] dp = new int[height][width];
34+
dp[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1;
35+
for(int i = 1; i < height; i++){
36+
dp[i][0] = obstacleGrid[i][0] == 1 ? 0 : dp[i-1][0];
37+
}
38+
for(int j = 1; j < width; j++){
39+
dp[0][j] = obstacleGrid[0][j] == 1 ? 0 : dp[0][j-1];
40+
}
41+
42+
for(int i = 1; i < height; i++){
43+
for(int j = 1; j < width; j++){
44+
if(obstacleGrid[i][j] == 1) dp[i][j] = 0;
45+
else {
46+
int paths = 0;
47+
if(obstacleGrid[i-1][j] == 0) paths += dp[i-1][j];
48+
if(obstacleGrid[i][j-1] == 0) paths += dp[i][j-1];
49+
dp[i][j] = paths;
50+
}
51+
}
52+
}
53+
CommonUtils.printMatrix(dp);
54+
return dp[height-1][width-1];
55+
}
56+
57+
public static void main(String...strings){
58+
UniquePathsII test = new UniquePathsII();
59+
// int[][] obstacleGrid = new int[3][3];
60+
// obstacleGrid[0][0] = 0;
61+
// obstacleGrid[0][1] = 0;
62+
// obstacleGrid[0][2] = 0;
63+
// obstacleGrid[1][0] = 0;
64+
// obstacleGrid[1][1] = 1;
65+
// obstacleGrid[1][2] = 0;
66+
// obstacleGrid[2][0] = 0;
67+
// obstacleGrid[2][1] = 0;
68+
// obstacleGrid[2][2] = 0;
69+
70+
// int[][] obstacleGrid = new int[1][2];
71+
// obstacleGrid[0][0] = 1;
72+
// obstacleGrid[0][1] = 0;
73+
74+
int[][] obstacleGrid = new int[2][2];
75+
obstacleGrid[0][0] = 0;
76+
obstacleGrid[0][1] = 0;
77+
obstacleGrid[1][0] = 0;
78+
obstacleGrid[1][1] = 1;
79+
80+
CommonUtils.printMatrix(obstacleGrid);
81+
System.out.println(test.uniquePathsWithObstacles(obstacleGrid));
82+
}
83+
84+
}

0 commit comments

Comments
 (0)