美文网首页
Q63 Unique Paths II

Q63 Unique Paths II

作者: 牛奶芝麻 | 来源:发表于2018-10-20 00:41 被阅读21次

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

相关文章

网友评论

      本文标题:Q63 Unique Paths II

      本文链接:https://www.haomeiwen.com/subject/vhrpzftx.html