63. Unique Paths II -Medium

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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值