[백준] 7569 토마토 Python

권희정·2024년 9월 26일

삼성전자

목록 보기
6/20

[백준] 7569 토마토 Python

평소에 2차원 리스트만 풀었는데, 이 문제는 3차원 리스트를 해야해서 조금 어려웠던 것 같다. 특히, z축을 어떻게 할까 고민이 많았는데 그냥 z축까지 추가하여 dz=[0,0,0,0,1,-1] 이런식으로 선언하고 for문을 6번 돌리면 된다. 나머지는 평소 bfs대로 구현하면 된다.

import sys
from collections import deque
sys.stdin=open("input.txt")

m,n,h=map(int,input().split()) #x,y,z
graph=[[list(map(int,input().split())) for _ in range(n)]for _ in range(h)]
#좌우상하위아래
dx=[-1,1,0,0,0,0] #m 좌우
dy=[0,0,-1,1,0,0] #n 상하
dz=[0,0,0,0,-1,1] #h 위아래

q=deque()
for i in range(h):
    for j in range(n):
        for k in range(m):
            if graph[i][j][k]==1:
                q.append((i,j,k)) #h,n,m

def bfs():
    while q:
        z,y,x=q.popleft()

        for i in range(6):
            nz=z+dz[i]
            ny=y+dy[i]
            nx=x+dx[i]

            if 0<=nz<h and 0<=ny<n and 0<=nx<m and graph[nz][ny][nx]==0:
                graph[nz][ny][nx]=graph[z][y][x]+1
                q.append((nz,ny,nx))

bfs()
cnt=0
for i in graph:
    for j in i:
        for k in j:
            if k==0:
                print(-1)
                exit()
        cnt=max(cnt,max(j))

print(cnt-1)
profile
데헷큥

0개의 댓글