490. The Maze

Question

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

Code

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

        visited = set()

        que = deque()

        que.append(start)
        visited.add((start[0], start[1]))

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

        
        while que:
            cur_row, cur_col = que.popleft()

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

            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]

                if (new_row, new_col) in visited:
                    continue
                
                visited.add((new_row, new_col))
                que.append([new_row, new_col])

        
        return False