当前位置: 首页 > 工具软件 > Entrance > 使用案例 >

Leetcode 1926. Nearest Exit from Entrance in Maze [Python]

宿文栋
2023-12-01

没啥好说的, BFS。代码里,遍历过的空位置其实可以不改,但是要过全部的TC的话,需要把遍历过的空位置改为墙。

class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
        Row = len(maze)
        Col = len(maze[0])
        x = entrance[0]
        y = entrance[1]
        dirt = [(1,0),(0,1),(-1,0),(0,-1)]
        que = collections.deque()
        que.append((x,y))
        meet = set()
        res = 0
        while que:
            size = len(que)
            for _ in range(size):
                i,j = que.popleft()
                meet.add((i,j))
                for di, dj in dirt:
                    newi = i + di
                    newj = j + dj
                    if 0 <= newi < Row and 0 <= newj < Col and maze[newi][newj] == '.' and (newi,newj) not in meet:
                        if newi == 0 or newi == Row - 1 or newj == 0 or newj == Col - 1:
                            return res + 1
                        else:
                            maze[newi][newj] = '+' #不加这行就会TLE
                            que.append((newi, newj))
            res += 1
        return -1
 类似资料: