본문 바로가기
코딩 테스트/문제 풀기

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

by hazel_ 2021. 3. 15.

n,m조심

from collections import deque
def solution(maps):
    n=len(maps[0])
    m=len(maps)

    visited = [[False]*n for _ in range(m)]

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

    queue = deque()
    queue.append((0, 0, 1))
    visited[0][0] = True

    while queue:
        x, y, cost = queue.popleft()

        # 상하좌우
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]

            if nx == m-1 and ny == n-1:
                return cost + 1
            elif nx >= 0 and ny >= 0 and nx < m and ny < n and maps[nx][ny]==1 and visited[nx][ny]==False:
                queue.append((nx, ny, cost+1))
                visited[nx][ny] = True
    return -1

댓글