Likou brushing notes: 63. Different paths II (62. Enhanced version of different paths, with obstacles added, or dynamic planning, directly set the template, and grasp the boundaries)

topic:

63. Different Paths II

A robot is located in the upper left corner of an mxn grid (the starting point is marked as "Start" in the figure below).

The robot can only move one step down or to the right at a time. The robot tries to reach the bottom right corner of the grid (labeled "Finish" in the image below).

Now consider that there are obstacles in the grid. So how many different paths will there be from the upper left corner to the lower right corner?

Insert picture description here

Obstacles and empty positions in the grid are represented by 1 and 0 respectively.

Example 1:

Insert picture description here

Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
Explanation:
There is an obstacle in the middle of the 3x3 grid.
There are 2 different paths from the upper left corner to the lower right corner:

  1. Right -> Right -> Down -> Down
  2. Down -> Down -> Right -> Right

Example 2:

Insert picture description here

Input: obstacleGrid = [[0,1],[0,0]]
Output: 1

prompt:

m == obstacleGrid.length
n == obstacleGrid[i].length
1 <= m, n <= 100
obstacleGrid[i][j] 为 0 或 1

Problem solution ideas:

If the grid is not an obstacle grid:
——If the grid is (0,0) position:
————The number of lines in the grid=1

Handling
of obstacles : There are obstacles = this road is not accessible = this grid has no route = the number of routes in this grid is 0.
Since the number of routes in each grid is initialized = 0,
if you encounter obstacles, you do not need to update the grid.

Handling of boundary conditions: If
there is no grid on the top, just look at the left
side. If there is no grid on the left, just look at the top

Problem solution python code:

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        #新建矩阵版
        height, width = len(obstacleGrid),len(obstacleGrid[0])
        store = [[0]*width for i in range(height)]

        #从上到下,从左到右
        for m in range(height):#每一行
            for n in range(width):#每一列
                if not obstacleGrid[m][n]: #如果这一格没有障碍物
                    if m == n == 0: #或if not(m or n)
                        store[m][n] = 1
                    else:
                        a = store[m-1][n] if m!=0 else 0 #上方格子
                        b = store[m][n-1] if n!=0 else 0 #左方格子
                        store[m][n] = a+b
        return store[-1][-1]

Author: xiao-yan-gou
link: https://leetcode-cn.com/problems/unique-paths-ii/solution/jian-ji-biao-ge-jie-shi-dong-tai-gui-hua-dpsi -lu-f/
Source: LeetCode (LeetCode) https://leetcode-cn.com/problems/unique-paths-ii/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/114604413