【DP】不同路径II

https://leetcode.cn/problems/unique-paths-ii/description/?envType=study-plan-v2&envId=top-interview-150

  1. 思路很简单,让obstacleGrid[i][j]代表走到ij所需要的步数,然后obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1]只需要把上方和左边的但是有很多神奇的corner case需要注意
  2. 比如开始就是障碍物就寄了,第一列和第一行的所有元素需要初始化为1
  3. 遇到障碍物的正确处理方法,需要把障碍物的格子可行步数设为零

这matrix的变量名真长

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        m = len(obstacleGrid)
        n = len(obstacleGrid[0])
        
        if obstacleGrid[0][0] == 1:  # Check if the starting cell is an obstacle
            return 0
        
        obstacleGrid[0][0] = 1  # Set the initial value
        
        # Initialize the first column
        for i in range(1, m):
            if obstacleGrid[i][0] == 1:
                obstacleGrid[i][0] = 0
            else:
                obstacleGrid[i][0] = obstacleGrid[i-1][0]
        
        # Initialize the first row
        for j in range(1, n):
            if obstacleGrid[0][j] == 1:
                obstacleGrid[0][j] = 0
            else:
                obstacleGrid[0][j] = obstacleGrid[0][j-1]
        
        # Fill the rest of the grid
        for i in range(1, m):
            for j in range(1, n):
                if obstacleGrid[i][j] == 1:
                    obstacleGrid[i][j] = 0
                else:
                    obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1]
        
        return obstacleGrid[-1][-1]
posted @ 2024-04-27 15:50  peterzh6  阅读(6)  评论(0编辑  收藏  举报