0063. Unique Paths II - chasel2361/leetcode GitHub Wiki

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
Now consider if some obstacles are added to the grids. How many unique paths would there be?
Note: m and n will be at most 100.

Example 1:
Input: [ [0,0,0], [0,1,0], [0,0,0] ]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right

https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png

這個問題跟Unique Paths很像,差別在於多了障礙物。

經過觀察之後可以知道,障礙物會使得其左方及上方無法通行,因此我們可以視其為 0 ,進而得出以下的作法

[1] 格線不存在,或障礙物放在最左上角的話就沒得走,回傳 0
[2] 如果取出的位置是障礙物 (值為 1 ),不做任何動作,若不為障礙物才進入接下來的動作
[3] 判斷是否為最上或最左方的 row 或 column,若是的話就只加總存在的項目

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        if not obstacleGrid or obstacleGrid[0][0] == 1: return 0  # [1]
        
        m, n = len(obstacleGrid), len(obstacleGrid[0])
    
        res = [[0]*n for _ in range(m)]
        res[0][0] = 1
    
        for i in range(m):
            for j in range(n):
                if obstacleGrid[i][j] != 1:  # [2]
                    if i > 0:  # [3]
                        res[i][j] += res[i - 1][j]
                    if j > 0:  # [3]
                        res[i][j] += res[i][j - 1]
        return res[-1][-1]

這樣的解法時間複雜度跟空間複雜度都是 O(N**2)