프로그래머스 - 게임 맵 최단거리

서유진·2022년 9월 24일
0

코테뿌셔

목록 보기
9/9

미숙한 제 풀이는 정답이 될 수 없으며, 이것보다 효율적인 코드는 당연히 존재합니다.
참고만 하여 주시고, 관련 피드백은 항상 환영합니다. 🤍

from collections import deque

def solution(maps):
    len_x, len_y = len(maps), len(maps[0])
    queue = deque([(0, 0)])
    directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]  # 상하좌우

    while queue:  # bfs 수행
        x, y = queue.popleft()
        for i in range(4):
            xx = x + directions[i][0]
            yy = y + directions[i][1]
            if 0 <= xx < len_x and 0 <= yy < len_y and maps[xx][yy] == 1:  
                maps[xx][yy] = maps[x][y] + 1
                queue.append((xx, yy))
    return maps[-1][-1] if maps[-1][-1] > 1 else -1
profile
Backend Dev.

0개의 댓글