Skip to content

Commit c9755aa

Browse files
committed
add solution of problem 63: unique paths II
1 parent ca4a2ba commit c9755aa

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

UniquePathsII63/README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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.

UniquePathsII63/Solution.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
}

0 commit comments

Comments
 (0)