Skip to content

Commit 8c2be79

Browse files
Time: 0 ms (100.00%), Space: 40.7 MB (50.19%) - LeetHub
1 parent 8978bee commit 8c2be79

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution { // DP, TOP-DOWN, TC: O(n+m)
2+
private int m = 0, n = 0;
3+
4+
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
5+
this.m = obstacleGrid.length;
6+
this.n = obstacleGrid[0].length;
7+
8+
int[][] dp = new int[m+1][n+1];
9+
10+
for(int[] arr : dp) {
11+
Arrays.fill(arr, -1);
12+
}
13+
14+
return solve(0, 0, obstacleGrid, dp);
15+
}
16+
private int solve(int i, int j, int[][] obstacleGrid, int[][] dp) {
17+
if(i >= m || j >= n || obstacleGrid[i][j] == 1) // reached out of bounds or encountered an obstacle
18+
return 0;
19+
20+
if(i == m - 1 && j == n - 1) // it's the bottom-right corner
21+
return 1;
22+
23+
if(dp[i][j] != -1)
24+
return dp[i][j];
25+
26+
int result = 0;
27+
28+
// Down move
29+
result += solve(i+1, j, obstacleGrid, dp);
30+
31+
// Right move
32+
result += solve(i, j+1, obstacleGrid, dp);
33+
34+
return dp[i][j] = result;
35+
}
36+
}

0 commit comments

Comments
 (0)