Question
*Follow up for “Unique Paths”:
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.
跟进”Unique Paths”,现在在表格中加一个障碍物(标记为1的是障碍物),有多少种路径可以到达终点。(m和n不会超过100)
Example
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]The total number of unique paths is 2.
Solution
动态规划解。原理和原题一样,取左边和上面的方法之和即可,对于障碍物,我们只需把它设为dp[i] = 0即可,这样不会影响到后面的计算。额外要考虑的是起始点和终点会不会有障碍物(居然有这样的测试集。。)。
class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ if len(obstacleGrid) == 0 or len(obstacleGrid[0]) == 0: return 0 # 如果起点或终点为1,则不可能有路径 if obstacleGrid[0][0] == 1 or obstacleGrid[-1][-1] == 1: return 0 dp = [[0 for _ in range(len(obstacleGrid[0]))] for _ in range(len(obstacleGrid))] dp[0][0] = 1 for index_r in range(len(obstacleGrid)): for index_c in range(len(obstacleGrid[0])): if index_c == 0 and index_r == 0: continue # 如果该表格是障碍,跳过 if obstacleGrid[index_r][index_c] == 1: continue # 第一行的来源只能为左边(障碍物表格的dp为0,所以其右边也都是0) if index_r == 0: dp[index_r][index_c] = dp[index_r][index_c - 1] # 第一行的来源只能为上面(障碍物表格的dp为0,所以其下边也都是0) elif index_c == 0: dp[index_r][index_c] = dp[index_r - 1][index_c] # 其他都是来自上面或左边(因为障碍的dp为0,所以它不影响结果) else: dp[index_r][index_c] = dp[index_r - 1][index_c] + dp[index_r][index_c - 1] return dp[-1][-1]