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

yewon Lee·2023년 6월 10일
0


😎코딩테스트 연습>깊이/너비 우선 탐색(DFS/BFS)>게임 맵 최단거리


from collections import deque
def solution(maps):
    answer = 0
    n = len(maps)
    m = len(maps[0])
    visited = [[False] * m for _ in range(n)]
    q = deque()
    
    dx = [1, -1, 0, 0]
    dy = [0, 0, 1, -1]
    
    q.append((0,0))
    visited[0][0] = True
    
    while q:
        pop_x, pop_y = q.popleft()
        
        for i in range(4):
            next_x = pop_x + dx[i]
            next_y = pop_y + dy[i]
            if next_x < 0 or next_x >= n or next_y < 0  or next_y >= m:
                continue
            if visited[next_x][next_y] == False and maps[next_x][next_y] == 1:
                q.append((next_x, next_y))
                visited[next_x][next_y] = True
                maps[next_x][next_y] = maps[pop_x][pop_y] + 1
    
    if maps[n-1][m-1] == 1:
        return -1
    
    return maps[n-1][m-1]
n,m 구분을 잘해야할 것 같다
profile
시작

0개의 댓글