2025-08-11 23:55:49 +09:00

48 lines
1.2 KiB
Python

import sys
from collections import deque
input = sys.stdin.readline
N, M, H = map(int, input().split())
visited = [[[-1]*N for _ in range(M)] for _ in range(H)]
emptyCount = 0
visitCount = 0
q = deque()
tomato = []
for z in range(H):
tomato.append([])
for y in range(M):
row = list(map(int, input().split()))
tomato[z].append(row)
for x in range(N):
if row[x] == 1 :
q.append((z,y,x))
visited[z][y][x] = 0
visitCount += 1
elif row[x] == -1 :
emptyCount += 1
dx = [1,-1,0,0,0,0]
dy = [0,0,1,-1,0,0]
dz = [0,0,0,0,1,-1]
dayMax = 0
while len(q) :
cz, cy, cx = q.popleft()
for i in range(6):
nz, ny, nx = cz + dz[i], cy + dy[i], cx + dx[i]
if 0<=nz<H and 0<=ny<M and 0<=nx<N and visited[nz][ny][nx] == -1 and tomato[nz][ny][nx] == 0:
q.append((nz,ny,nx))
visitCount += 1
visited[nz][ny][nx] = visited[cz][cy][cx] + 1
if visited[nz][ny][nx] > dayMax :
dayMax = visited[nz][ny][nx]
if N*M*H == visitCount + emptyCount :
print(dayMax)
else :
print(-1)