Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit c35778c

Browse files
committedSep 10, 2016
Lintcode/src/chapter4_DynamicProgrammingI/UniquePathsII.java
1 parent 2f34d85 commit c35778c

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
 
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package chapter4_DynamicProgrammingI;
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+
Notice
9+
10+
m and n will be at most 100.*/
11+
public class UniquePathsII {
12+
13+
/**
14+
* @param obstacleGrid: A list of lists of integers
15+
* @return: An integer
16+
*/
17+
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
18+
// write your code here
19+
if(obstacleGrid == null || obstacleGrid.length == 0) return 0;
20+
int m = obstacleGrid.length, n = obstacleGrid[0].length;
21+
int[][] ways = new int[m][n];
22+
23+
for(int i = 0; i < m; i++){
24+
if(obstacleGrid[i][0] == 0) ways[i][0] = 1;
25+
else {
26+
while(i < m){
27+
ways[i][0] = 0;
28+
i++;
29+
}
30+
}
31+
}
32+
33+
for(int j = 0; j < n; j++){
34+
if(obstacleGrid[0][j] == 0) ways[0][j] = 1;
35+
else {
36+
while(j < n){
37+
ways[0][j] = 0;
38+
j++;
39+
}
40+
}
41+
}
42+
43+
for(int i = 1; i < m; i++){
44+
for(int j = 1; j < n; j++){
45+
if(obstacleGrid[i][j] == 1) ways[i][j] = 0;
46+
else ways[i][j] = ways[i-1][j] + ways[i][j-1];
47+
}
48+
}
49+
50+
return ways[m-1][n-1];
51+
}
52+
53+
}

0 commit comments

Comments
 (0)
Failed to load comments.