第八週 LeetCode.63. Unique Paths II 題解

這是一題動態規劃的題目。若一個格子可達,則到達這個格子的路徑數等於到達其上一個格子的路徑數與到達其左格子的路徑數的和;否則到達這個格子的路徑數爲0. 


題目:

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.


題解:

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        #nums[i][j]表示到達(i, j)這個位置的路徑數
        nums = obstacleGrid
        for j in range(0, len(obstacleGrid[0])):
            nums[0][j] = 1 - obstacleGrid[0][j]
        for i in range(1, len(obstacleGrid)):
            nums[i][0] = 0 if obstacleGrid[i][0] else nums[i-1][0]
            for j in range(1, len(obstacleGrid[i])):
                nums[i][j] = 0 if obstacleGrid[i][j] else nums[i-1][j] + nums[i][j-1]
        return nums[-1][-1]


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章