63 different paths II

Title: mxn a robot in a top left corner of the grid (starting point figure below labeled "Start") of the robot can only move one step down or to the right. Robot trying to reach the lower right corner of the grid (figure below labeled "Finish"). Now consider the grid obstructions. So how many different paths from top left to bottom right corner there will be?

Source: https://leetcode-cn.com/problems/unique-paths-ii/

Act one: their own code

Ideas: If you encounter an obstacle, the position directly set to 0, the key is to deal with the obstacle behind the position, due to obstacles set to 0, and can still be added up.

# Execute when used: 44 ms, beat all python3 submission of 98.81% of user 
# memory consumption: 12.5 MB, defeated 99.13% of users in all python3 submission 
from Typing Import List
 class Solution:
     DEF uniquePathsWithObstacles (Self, obstacleGrid: List [List [int]]) -> int: 
        m = len (obstacleGrid) 
        n- = len (obstacleGrid [0])
         # DP is recorded in the number of paths reaches the position 
        DP = [[. 1] n-* for I in Range (m)]
         # of the first row and first column number of the path behind the obstacle is necessarily 0, 0 is set to 
        # the back of the first row dp obstacle elements are set to 0 
        for P inRange (n-):
             IF obstacleGrid [0] [P] == 0:
                 Pass 
            the else : 
                DP [0] [P] = 0
                 the while P +. 1 < n-: 
                    P = P +. 1 
                    DP [0] [P] = 0
                 BREAK 
        # the dp obstacle behind the first row of the elements are set 0 
        for P in Range (m):
             IF obstacleGrid [P] [0] == 0:
                 Pass 
            the else : 
                dp [P] [0] = 0
                 the while P +1 <m: 
                    P = P +. 1 
                    dp [P] [0] = 0
                 BREAK 
        # with Method 62, if an obstacle is encountered, and direct the respective positions facing dp 0 
        for I in Range (. 1 , m):
             for J in Range (. 1 , n-):
                 IF obstacleGrid [I] [J] == 0: 
                    DP [I] [J] = DP [I] [J -. 1] + DP [I -. 1 ] [J]
                 the else : 
                    DP [I] [J] = 0
         return DP [-1] [-. 1 ]
 IF  the __name__ == '__main__ ' : 
    duixiang = Solution () 
    A = duixiang.uniquePathsWithObstacles ( 
          [[ . 1], [0]])
View Code

Guess you like

Origin www.cnblogs.com/xxswkl/p/12093477.html