This is based on this leetcode question. I get the correct answer, but I know it could be much, much cleaner. I also know there is supposed to be an O(n) space solution, but I'm not sure how to implement cleanly.
It is a dynamic programming problem, I tried to add some helpful code comments, I know it's pretty messy so thank you for your review.
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
#initialize memoization array
memo = [[-1 for i in range(len(obstacleGrid[0]))] for j in range(len(obstacleGrid))]
#add known values before any calculation (last row and last column)
memo[len(memo)-1][len(memo[0])-1] = 1
for i in range(len(memo[0])-2,-1,-1):
if obstacleGrid[len(memo)-1][i] != 1:
memo[len(memo)-1][i] = memo[len(memo)-1][i+1]
else:
memo[len(memo)-1][i] = 0
for j in range(len(memo)-2,-1,-1):
if obstacleGrid[j][len(memo[0])-1] != 1:
memo[j][len(memo[0])-1] = memo[j+1][len(memo[0])-1]
else:
memo[j][len(memo[0])-1] = 0
if obstacleGrid[len(memo)-1][len(memo[0])-1] == 1:
return 0
#does calculations
def helper(row,col):
nonlocal memo
if obstacleGrid[row][col] == 1:
return 0
if memo[row][col] == -1:
memo[row][col] = helper(row+1,col) + helper(row,col+1)
return memo[row][col]
return helper(0,0)