63. Unique Paths II

63. Unique Paths II

1 题目

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?

dp

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

2. 思路

本题和之前的 62 Unique Paths 都是求机器人从左上角到右下角有几种走法。所不同的是,这次机器人行走的过程中有了障碍。如果输入的矩阵中,obstacleGrid[i] [j] == 1 则代表了这个地方不能行走。同样,本题也是使用动态规划完成。设dp [i] [j] 是机器人走到第i行,第j列的走法总数:

  1. 如果obstacleGrid[i] [j] == 1 则,dp[i] [j] = 0 。如果当前步有障碍,则走法肯定是0
  2. 如果obstacleGrid[i] [j] != 1 则,dp[i] [j] = dp[i-1] [j] + dp[j-1] [i]

构建完递推表达式,还需要初始化下第0行和第0列,构建的规则和上面的递推式是一样的,只不过i和j换成了0:

row = len(obstacleGrid) 
        col = len(obstacleGrid[0]) 
        dp = [  [ 0 for j in range(col)] for i in range(row) ] 
        
        if obstacleGrid[0][0] == 1 :
            return 0 
        else:
            dp[0][0] = 1 
    
        for i in range(1,row):
            if obstacleGrid[i][0] == 1 :
                dp[i][0] = 0 
            else:
                dp[i][0] = dp[i-1][0]
                
        for j in range(1,col):
            if obstacleGrid[0][j] == 1 :
                dp[0][j] = 0 
            else:
                dp[0][j] = dp[0][j-1]

3. 实现

class Solution(object):
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        row = len(obstacleGrid) 
        col = len(obstacleGrid[0]) 
        dp = [  [ 0 for j in range(col)] for i in range(row) ] 
        
        if obstacleGrid[0][0] == 1 :
            return 0 
        else:
            dp[0][0] = 1 
    
        for i in range(1,row):
            if obstacleGrid[i][0] == 1 :
                dp[i][0] = 0 
            else:
                dp[i][0] = dp[i-1][0]
                
        for j in range(1,col):
            if obstacleGrid[0][j] == 1 :
                dp[0][j] = 0 
            else:
                dp[0][j] = dp[0][j-1]
                
        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-1][j] + dp[i][j-1]
        return dp[row-1][col-1]
                
                
posted @ 2019-05-26 14:57  bush2582  阅读(81)  评论(0编辑  收藏  举报