这是一题动态规划的题目。若一个格子可达,则到达这个格子的路径数等于到达其上一个格子的路径数与到达其左格子的路径数的和;否则到达这个格子的路径数为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]