Leetcode - 63 different paths II python

Disclaimer: This article is original, All Rights Reserved https://blog.csdn.net/weixin_41864878/article/details/90520331

A robot located in a left corner mxn grid (starting point figure below labeled "Start").

The robot can only move one step to the right or down. Robot trying to reach the bottom right corner of the grid (in the following figure labeled "Finish").

Now consider the grid obstructions. So how many different paths from top left to bottom right corner there will be?

Empty grid positions and the obstacle respectively 1 and 0 to represent.

Description: the values ​​of m and n is not more than 100.

Example 1:

Input: [[0,0,0], [0,1,0], [0,0,0]] Output: 2 Explanation: the middle of a 3x3 grid obstacle.
From top left to bottom right corner of a total of two different paths:

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

There are many boundary conditions, and then taken into 62 do not differ from
the basic equation:
When not an obstacle, step [i] [j] = step [i-1] [j] + step [i] [j-1]
is the obstacle, step [i] [j] = 0

class Solution(object):
    def uniquePathsWithObstacles(self, obstacleGrid):
        """
        :type obstacleGrid: List[List[int]]
        :rtype: int
        """
        if not obstacleGrid: return 0
        if obstacleGrid[len(obstacleGrid)-1][len(obstacleGrid[0])-1]: return 0 #如果右下角是个障碍物那么就不能到达,返回0
        if len(obstacleGrid) == len(obstacleGrid[0]) == 1: return 1 #只有起始点(这里题目好像默认起始点不会是障碍点的)
        
        #初始矩阵的构建,非常重要,这里全部要按零初始化,第一行或者第一列出现障碍物后,后面的值要全部都是0
        step = [[0 for i in range(len(obstacleGrid[0]))] for j in range(len(obstacleGrid))]
        for i in range(len(obstacleGrid[0])):
            if not obstacleGrid[0][i]:
                step[0][i] = 1
            else:
                if len(obstacleGrid) == 1: return 0  #如果是单行,出现障碍物,不能到达
            	break
        for i in range(len(obstacleGrid)):
            if not obstacleGrid[i][0]:
                step[i][0] = 1
            else: 
            	if len(obstacleGrid[0]) == 1: return 0
            	break
            
        #标准动规   
        for i in range(1, len(obstacleGrid)):
            for j in range(1, len(obstacleGrid[0])):
                step[i][j] = step[i-1][j] + step[i][j-1] if not obstacleGrid[i][j] else 0
        return step[len(obstacleGrid)-1][len(obstacleGrid[0])-1] 

Guess you like

Origin blog.csdn.net/weixin_41864878/article/details/90520331