1. 程式人生 > >LeetCode63: Unique Paths II

LeetCode63: Unique Paths II

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?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

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

LeetCode:連結

一定要考慮特殊情況,如果obstacle在(0,0),後面都過不去;如果obstacle在第零行或者是第零列,那麼這一行或是這一列後面的都過不去了。相比61題,判斷條件要增加了。

class Solution(object):
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        '''網格不存在 直接返回0'''
        if not obstacleGrid:
            return 0
        '''網格第一處是障礙,後面的都過不去'''
        if obstacleGrid[0][0] == 1:
            return 0
        m, n = len(obstacleGrid), len(obstacleGrid[0])
        matrix = [[0]*n for row in range(m)]
        '''判斷第一列有沒有障礙,如果有,後面的都過不去'''
        for i in range(m):
            if obstacleGrid[i][0] == 0:
                matrix[i][0] = 1
            else:
                break
        '''判斷第一行有沒有障礙,如果有,後面的都過不去'''
        for j in range(n):
            if obstacleGrid[0][j] == 0:
                matrix[0][j] = 1
            else:
                break
        '''判斷中間的數有沒有障礙'''
        for i in range(1, m):
            for j in range(1, n):
                if obstacleGrid[i][j] == 1:
                    matrix[i][j] = 0
                else:
                    matrix[i][j] = matrix[i][j-1] + matrix[i-1][j]
        return matrix[m-1][n-1]