Skip to content

Commit 933b99e

Browse files
Add java solution to LC63
1 parent a2dac93 commit 933b99e

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

LC63-Unique-Paths-II.java

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*
2+
A robot is located at the top-left corner of a m x n grid (marked
3+
'Start' in the diagram below).
4+
5+
The robot can only move either down or right at any point in time.
6+
The robot is trying to reach the bottom-right corner of the grid
7+
(marked 'Finish' in the diagram below).
8+
9+
Now consider if some obstacles are added to the grids. How many
10+
unique paths would there be?
11+
12+
An obstacle and space is marked as 1 and 0 respectively in the grid.
13+
14+
Example 1:
15+
Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
16+
Output: 2
17+
Explanation: There is one obstacle in the middle of the 3x3 grid above.
18+
There are two ways to reach the bottom-right corner:
19+
1. Right -> Right -> Down -> Down
20+
2. Down -> Down -> Right -> Right
21+
22+
Example 2:
23+
Input: obstacleGrid = [[0,1],[0,0]]
24+
Output: 1
25+
26+
27+
Constraints:
28+
m == obstacleGrid.length
29+
n == obstacleGrid[i].length
30+
1 <= m, n <= 100
31+
obstacleGrid[i][j] is 0 or 1.
32+
*/
33+
34+
class Solution {
35+
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
36+
int m = obstacleGrid.length;
37+
int n = obstacleGrid[0].length;
38+
int[] paths = new int[n];
39+
if ((obstacleGrid[0][0] == 1) | (obstacleGrid[m-1][n-1] == 1)){
40+
return 0;
41+
}
42+
int i = 0;
43+
while ((i < n) && (obstacleGrid[0][i] == 0)){
44+
paths[i] = 1;
45+
i++;
46+
}
47+
for (i=1; i < m; i++){
48+
if (obstacleGrid[i][0] == 1){
49+
paths[0] = 0;
50+
}
51+
for (int j = 1; j < n; j++){
52+
if (obstacleGrid[i][j] == 0){
53+
paths[j] = paths[j] + paths[j-1];
54+
} else {
55+
paths[j] = 0;
56+
}
57+
}
58+
}
59+
return paths[n-1];
60+
}
61+
}

0 commit comments

Comments
 (0)