[LeetCode] 1926. Nearest Exit from Entrance in Maze

김민우·2022년 11월 21일
0

알고리즘

목록 보기
71/189

- Problem

1926. Nearest Exit from Entrance in Maze

- 내 풀이

class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
        M, N = len(maze), len(maze[0])
        q = collections.deque([entrance + [0]])
        while q:
            y, x, count = q.popleft()
            if (x in (0, N-1) or y in (0, M-1)) and [y, x] != entrance:
                return count
            
            for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
                nx = x + dx
                ny = y + dy
                
                if 0 <= nx < N and 0 <= ny < M and maze[ny][nx] == ".":
                    maze[ny][nx] = '+'
                    q.append([ny, nx, count + 1])
                    
        return -1

- 결과

profile
Pay it forward.

0개의 댓글