PS

프로그래머스 1844 Python [게임 맵 최단거리]

firsthg 2026. 8. 13. 12:19
from collections import deque

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

def solution(maps):
    n, m = len(maps), len(maps[0])
    visited = [[False] * m for _ in range(n)]  # 방문했는지 체크하는 visited 배열 초기화
    q = deque([(0, 0)])  # 큐 초기화
    while q:
        x, y = q.popleft()
        visited[x][y] = True
        for k in range(4):
            nx, ny = x + dx[k], y + dy[k]
            if (0 <= nx < n and 0 <= ny < m) and (maps[nx][ny] == 1):
                if visited[nx][ny] != True:
                    visited[nx][ny] = True
                    maps[nx][ny] = maps[x][y] + 1
                    if nx == n - 1 and ny == m - 1:  # 목적지에 다다른 경우 조기 종료
                        return maps[nx][ny]
                    q.append((nx, ny))
    return -1  # 전체를 돌아도 목적이에 도달하지 못하는 경우