L2 : 게임 맵 최단거리 Python

jhyunn·2023년 1월 19일
0

Programmers

목록 보기
41/69

L2 : 게임 맵 최단거리 Python

https://school.programmers.co.kr/learn/courses/30/lessons/1844

from collections import deque

def solution(maps):
    answer = []
    max_cnt = sum([m.count(1) for m in maps])
    visited = maps[:][:]
    
    dq = deque()
    dq.append([0, 0, 1])
    visited[0][0] = 0 # 방문하면 벽으로 만들어버림
    
    while dq: # BFS
        i, j, cnt = dq.popleft() # bfs는 popleft !!
        if [i, j] == [len(maps)-1, len(maps[0])-1]: # 도착하면 cnt를 저장
            answer.append(cnt)
        for k, l in [[-1, 0], [1, 0], [0, -1], [0, 1]]: # 4방향으로 이동
            if i+k>=0 and j+l>=0 and i+k<len(maps) and j+l<len(maps[0]): #map을 벗어나지 않아야함
                if maps[i+k][j+l] == 1 and visited[i+k][j+l] == 1:
                    dq.append([i+k, j+l, cnt+1])
                    visited[i+k][j+l] = 0
                    
    if len(answer) == 0:
        return -1
    return min(answer)

#BFS #최단거리

profile
https://github.com/Sungjeonghyun

0개의 댓글