Python Solution:
class Solution: def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: m = len(obstacleGrid) n = len(obstacleGrid[0]) #1. The first cell #2. The first column #3. The first row #4. The cells except for the first 3 cases # If the starting cell has an obstacle, there would be no path to the destination. if obstacleGrid[0][0] == 1: return 0 else: obstacleGrid[0][0] = 1 # First column for i in range(1,m): if obstacleGrid[i][0] == 1: obstacleGrid[i][0] = 0 else: obstacleGrid[i][0]=obstacleGrid[i-1][0] # First row for j in range(1, n): if obstacleGrid[0][j] == 1: obstacleGrid[0][j] = 0 else: obstacleGrid[0][j]=obstacleGrid[0][j-1] # Starting from cell(1,1) fill up the values # No. of unique paths of reaching cell[i][j] = cell[i - 1][j] + cell[i][j - 1] for i in range(1,m): for j in range(1,n): if obstacleGrid[i][j] == 0: obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1] else: obstacleGrid[i][j] = 0 # Return value stored in rightmost bottommost cell. That is the destination. return obstacleGrid[m-1][n-1] #Time complixity: O(mn) #Space complexity: O(1)
Time Complexity: O(mn)
Space Complexity: O(1)
Feeling tired? You can also try our free online no-installation required casual games: Here Please consider to follow my youtube channel to support me: