Skip to content

Commit 248cd10

Browse files
committed
Added top-down DP for unique paths ii
1 parent 5e176d0 commit 248cd10

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

unique_paths_ii/solution2.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution:
2+
# @param obstacleGrid, a list of lists of integers
3+
# @return an integer
4+
def uniquePathsWithObstacles(self, obstacleGrid):
5+
n = len(obstacleGrid)
6+
m = len(obstacleGrid[0])
7+
t = [[-1 for i in range(m)] for j in range(n)]
8+
return self.unique_paths(obstacleGrid, m - 1, n - 1, t)
9+
10+
def unique_paths(self, grid, x, y, t):
11+
if x == 0 and y == 0:
12+
return 1 if grid[y][x] == 0 else 0
13+
elif t[y][x] != -1:
14+
return t[y][x]
15+
elif x > 0 and y == 0:
16+
if grid[y][x] == 1:
17+
t[y][x] = 0
18+
else:
19+
t[y][x] = self.unique_paths(grid, x - 1, y, t)
20+
return t[y][x]
21+
elif y > 0 and x == 0:
22+
if grid[y][x] == 1:
23+
t[y][x] = 0
24+
else:
25+
t[y][x] = self.unique_paths(grid, x, y - 1, t)
26+
return t[y][x]
27+
else:
28+
if grid[y][x] == 1:
29+
t[y][x] = 0
30+
else:
31+
a = self.unique_paths(grid, x - 1, y, t)
32+
b = self.unique_paths(grid, x, y - 1, t)
33+
t[y][x] = a + b
34+
return t[y][x]

0 commit comments

Comments
 (0)