Q63 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
解题思路:

这个题就不能像 Q62 Unique Paths 使用数学技巧求解了。但是我们同样可以使用动态规划,只不过有障碍物的地方 dp[i][j] 的值为 0 即可。

具体做法:刚开始初始化 dp[n][m] 时都要初始化为 0(因为可能有障碍)。对于第一行和第一列单独计算,第一行从左到右(或第一列从上到下)如果没有障碍,初始化为 1;有障碍,第一行(或第一列)后面的都要是 0 (因为后面的路不通)。在计算中间结点时,如果有障碍,dp[i][j] 的值也是0;没有障碍就更新 dp[i][j] 的值:dp[i][j] = dp[i][j-1] + dp[i-1][j]

Python 实现:
class Solution:
    # DP
    # Time: O(n^2)
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        row = len(obstacleGrid)
        col = len(obstacleGrid[0])
        if obstacleGrid[row-1][col-1] == 1:
            return 0
        dp = [[0 for _ in range(col)] for _ in range(row)]
        for i in range(row):  # 初始化第一行,遇到阻碍后面都是0
            if obstacleGrid[i][0] == 0:
                dp[i][0] = 1 
            else:
                break
        for j in range(col):  # 初始化第一列,遇到阻碍后面都是0
            if obstacleGrid[0][j] == 0:
                dp[0][j] = 1
            else:
                break
        for i in range(1, row):
            for j in range(1, col):
                if obstacleGrid[i][j] == 1:
                    dp[i][j] = 0
                else:
                    dp[i][j] = dp[i][j-1] + dp[i-1][j]
        return dp[i][j]

obstacleGrid1 = [[0,1,0],[0,1,0],[0,0,0]]
obstacleGrid2 = [[0,0,0],[0,1,0],[0,0,0]]
print(Solution().uniquePathsWithObstacles(obstacleGrid1))  # 1
print(Solution().uniquePathsWithObstacles(obstacleGrid2))  # 2
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 动态规划(Dynamic Programming) 本文包括: 动态规划定义 状态转移方程 动态规划算法步骤 最长...
    廖少少阅读 3,619评论 0 18
  • 这是一款帮助您睡眠、放松减压、冥想或者专注的健康辅助类APP。在美好的自然声环绕中,再配合DHGS实验室调制的双声...
    速递君阅读 518评论 0 0
  • 优秀是一种习惯,但是习惯成自然,往往也成了阻碍成长的因素。优秀并不是错,错的是你以为自己很优秀,而事实不然。 壹 ...
    九点半月光阅读 2,954评论 18 45
  • 黄昏带着一丝不舍 不堪回首 最是那告别时的温柔 挥一挥手 不是我不留 而是我留了你也注定要走
    简村小吹阅读 1,114评论 12 14
  • 巴山蜀地,闷热潮湿的夏夜,我关了灯,躺在床上仰望黑灰的天花板。 我住的这家小青旅在22楼,白天的时候,从窗前望出去...
    思寰阅读 312评论 0 0

友情链接更多精彩内容