oohyoo 님의 블로그

[Python] 프로그래머스 - 미로 탐험2 본문

코딩테스트

[Python] 프로그래머스 - 미로 탐험2

oohyoo 2025. 2. 3. 23:33

[문제]

[풀이]

 

#입력과 출력을 자유롭게 작성해주세요
from collections import deque

def solution(house, h, w):
    queue = deque([(h, w, 0)])
    dh = [-1, 0, 1, 0]
    dw = [0, 1, 0, -1]
    visited = [[-1]*W for _ in range(H)]
    
    while queue:
        x, y, dist = queue.popleft()
        
        for d in range(4):
            cx = x+dh[d]
            cy = y+dw[d]
            if 0<=cx<H and 0<=cy<W and house[cx][cy] == 1 and visited[cx][cy] == -1:
                visited[cx][cy] +=1
                house[cx][cy] = dist
                queue.append((cx, cy, dist+1))
                
    output=''
    for i in range(H):
        for j in range(W):
            if (house[i][j] ==1 and visited[i][j] == -1):
                output += '-1 '
            elif (house[i][j]!=0):
                output = output + str(house[i][j]+1) + ' '
            else:
                output = output + str(house[i][j]) + ' '
        output = output.strip() + '\n'
    return str(output.strip())

house = []
H, W = map(int, input().split())
for ht in range(H):
    temp = list(map(int, input().strip()))
    if 2 in temp:
        w = temp.index(2)
        h = ht
    house.append(temp)

print(solution(house, h, w))
반응형