코딩 테스트/Level 2

게임 맵 최단거리

컴닥 2021. 4. 10. 23:06
반응형

게임 맵 최단거리
찾아라 프로그래밍 마에스터 
1268명 완료

programmers.co.kr/learn/courses/30/lessons/1844

 

코딩테스트 연습 - 게임 맵 최단거리

[[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]] 11 [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]] -1

programmers.co.kr

from collections import deque


def solution(maps):
    n, m = len(maps), len(maps[0])
    visited = {(0, 0)}
    que = deque([[0, 0, 1]])
    while que:
        x, y, cnt = que.popleft()
        for a, b in ((0, 1), (1, 0), (-1, 0), (0, -1)):
            nx, ny = x + a, y + b
            if nx == n - 1 and ny == m - 1:
                return cnt + 1
            elif 0 <= nx < n and 0 <= ny < m and maps[nx][ny] and (nx, ny) not in visited:
                que.append([nx, ny, cnt + 1])
                visited.add((nx, ny))
                maps[x][y] = 0
    return -1
반응형