[Dynamic Programming] [Leetcode] 63. Unique Paths II

1. Title description

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?
Insert picture description here
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. Thinking analysis

This question is also a basic question for investigating dynamic programming algorithms. Simple analysis can clarify the idea. We denote the number of paths to the position (i, j) as f(i, j). Then it is clear that there are three rules as follows:

  1. If there is an obstacle at (i, j), then obviously we can't reach the position (i, j), f(i, j) = 0
  2. Since it can only move to the right or down, there are only two ways to reach the position (i, j), move one step downward from the position (i -1, j), and move from the position (i, j -1) to Move one step to the right. So the number of paths to (i, j) should be the sum of the number of paths to (i -1, j) and (i, j-1). That is, f(i, j) = f(i-1, j) + f(i, j -1)
  3. When there is no obstacle at (0, 0), f(0,0) = 1, and when there is an obstacle at (0,0), it can’t go, f(0,0) = 0
    according to these three rules , You can write the code.

3. Code implementation

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        if (not obstacleGrid) or (obstacleGrid[0][0] == 1):
            return 0
        row = len(obstacleGrid)
        colum = len(obstacleGrid[0])
        res = [[0 for i in range(colum)] for j in range(row)]  
        for i in range(row):
            for j in range(colum):
                if (i == 0  and j == 0):
                    res[i][j] = 1
                    continue
                if (obstacleGrid[i][j] == 1):
                    res[i][j] = 0
                else:   
                    res[i][j] = 0
                    if (i > 0):
                        res[i][j] += res[i - 1][j]
                    if (j > 0): 
                        res[i][j] += res[i][j - 1]
        return res[row -1][colum - 1]         
if __name__ == '__main__':
    grid = [
    [0,0,0],
    [0,1,0],
    [0,0,0]
    ]
    res = Solution()
    ans = res.uniquePathsWithObstacles(grid)
    print(ans)

Guess you like

Origin blog.csdn.net/ww1473345713/article/details/86743584