505. The Maze II

Question

CleanShot 2024-09-11 at 18.29.16@2x.png

Code

class Solution:
    def shortestDistance(self, maze: List[List[int]], start: List[int], destination: List[int]) -> int:
        
        ROW, COL = len(maze), len(maze[0])

        visited = set()

        heap = []

        heapq.heappush(heap, (0, start[0], start[1]))

        direction = [[1, 0], [0, -1], [-1, 0], [0, 1]]

        
        while heap:
            cur_length, cur_row, cur_col = heapq.heappop(heap)

            if cur_row == destination[0] and cur_col == destination[1]:
                return cur_length

            if (cur_row, cur_col) in visited:
                continue

            visited.add((cur_row, cur_col))

            for i in range(4):
                new_row = cur_row
                new_col = cur_col

                while 0 <= (new_row + direction[i][0]) < ROW and 0 <= (new_col + direction[i][1]) < COL and maze[new_row + direction[i][0]][new_col + direction[i][1]] == 0:
                    new_row += direction[i][0]
                    new_col += direction[i][1]
                
                heapq.heappush(heap, (cur_length + abs(new_row - cur_row) + abs(new_col - cur_col), new_row, new_col))

        return -1