본문 바로가기
PROGRAMMERS

[프로그래머스/파이썬] 게임 맵 최단거리

by kode-daks 2025. 2. 6.

내 풀이

from collections import deque


def solution(maps):
    answer = 0
    n, m = len(maps[0]), len(maps)
    direction = [(0,1), (0,-1), (1,0), (-1,0)] # 가야 할 방향
    
    def bfs(x, y):
        queue = deque()
        queue.append((x,y))
        
        while queue:
            x,y = queue.popleft()
            for dx, dy in direction:
                nx, ny = x+dx, y+dy
                if 0 <= nx < n and 0 <= ny < m: # 맵 범위를 벗어나지 않았을 때
                    if maps[ny][nx] == 1: # 갈 수 있는 길 + 지나지 않은 길
                        maps[ny][nx] += maps[y][x] # 지나온 거리를 더해주기 때문
                        queue.append((nx, ny))
    
    bfs(0,0)
    # 마지막 값이 지나온 거리로 바뀌지 않고 1로 남아있다면 도달하지 못했다는 뜻
    return -1 if maps[-1][-1] == 1 else maps[-1][-1]

 

메모

자주 풀어야 익숙해지지!