Question 63 Unique Paths 2

The description of the question is in the following link:

https://leetcode.com/problems/unique-paths-ii/

My code:

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        Mat = [[1]*len(obstacleGrid[0]) for _ in range(len(obstacleGrid))];
        
        for row in range(len(obstacleGrid)):
            if row == 0 :
                for col in range(len(obstacleGrid[0])):

                        if obstacleGrid[row][col] ==1:
                            Mat[row][col] =0;
                        else:
                            Mat[row][col] = Mat[row][col-1];

            else:
                for col in range(len(obstacleGrid[0])):
                    if col == 0:
                        if obstacleGrid[row][col] == 1:
                            Mat[row][col] = 0;
                        else:
                            Mat[row][col] = Mat[row-1][col];
                    else:
                        if obstacleGrid[row][col] == 1:
                            Mat[row][col] = 0;
                        else:
                            Mat[row][col] = Mat[row][col-1]+Mat[row-1][col];
        return Mat[len(obstacleGrid)-1][len(obstacleGrid[0])-1];

Explanation: This part of the code is very similar to the previous part. Except that we need to be very careful about the situation that whenever there is a rock, we need to set the path number at that part as 0. I start from row 0 because there might be an obstacle on the row 0 or col 0, so we need to take this into consideration.

Leave a comment