首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q63 Unique Paths II

Q63 Unique Paths II

作者头像
echobingo
发布2018-11-07 15:31:07
3430
发布2018-11-07 15:31:07
举报

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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.10.20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example 1:
  • 解题思路:
    • Python 实现:
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档