Unique Paths II

Key Idea

Solution

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:

        # Dynamic Programming problem
        m = len(obstacleGrid)
        n = len(obstacleGrid[0])
        dp = [[ 1 - value for value in row] for row in obstacleGrid]
        
        # Edge case
        if dp[0][0] == 0:
            return 0
        
        # Initialize first column
        for i in range(1, m):
            dp[i][0] = dp[i][0] * dp[i - 1][0]

        # Initialize first row
        for j in range(1, n):
            dp[0][j] = dp[0][j] * dp[0][j - 1]

        # ObstacleGrid
        # 0,0,0
        # 0,1,0
        # 0,0,0

        # DP - Basically the "reverted"
        # 1,1,1
        # 1,0,1
        # 1,1,1

        # We can NOT include a bath that is marked 1
        for i in range(1,m):
            for j in range(1,n):
                if obstacleGrid[i][j] == 0:
                    dp[i][j] = dp[i-1][j] + dp[i][j-1] 
                else:
                    dp[i][j] = 0
        return dp[m-1][n-1]

Complexity