https://www.acmicpc.net/problem/7576
https://www.acmicpc.net/problem/7569
from collections import deque
import sys
def bfs():
# 토마토 queue 사용
q = deque()
cnt = 0
visited = [[0] * N for _ in range(M)]
for m in range(M):
for n in range(N):
if arr[m][n] == 1:
q.append((m, n))
visited[m][n] = 1
elif arr[m][n] == 0:
cnt += 1
while q:
cm, cn = q.popleft()
for i, j in ((0, 1), (0, -1), (1, 0), (-1, 0)):
rm, rn = i + cm, j + cn
if 0 <= rm < M and 0 <= rn < N and arr[rm][rn] == 0:
if visited[rm][rn] == 0:
q.append((rm, rn))
visited[rm][rn] = visited[cm][cn] + 1
cnt -= 1
if cnt == 0:
return visited[cm][cn] - 1
else:
return -1
N, M = map(int, sys.stdin.readline().split())
arr = list()
for i in range(M):
arr.append(list(map(int, sys.stdin.readline().split())))
print(bfs())
import sys
from collections import deque
def bfs():
q = deque()
v = [[[0] * M for _ in range(N)] for _ in range(H)]
cnt = 0
for h in range(H):
for n in range(N):
for m in range(M):
if arr[h][n][m] == 1:
q.append((h, n, m))
v[h][n][m] = 1
elif arr[h][n][m] == 0:
cnt += 1
while q:
ch, cn, cm = q.popleft()
for h, n, m in ((0, 1, 0), (0, 0, 1), (0, -1, 0), (0, 0, -1), (1, 0, 0), (-1, 0, 0)):
rh, rn, rm = ch + h, cn + n, cm + m
if 0 <= rh < H and 0 <= rn < N and 0 <= rm < M and arr[rh][rn][rm] == 0 and v[rh][rn][rm] == 0:
q.append((rh, rn, rm))
v[rh][rn][rm] = v[ch][cn][cm] + 1
cnt -= 1
if cnt == 0:
return v[ch][cn][cm] - 1
else:
return -1
M, N, H = map(int, sys.stdin.readline().split())
arr = [[list(map(int, input().split())) for _ in range(N)] for _ in range(H)]
ans = bfs()
print(ans)