from collections import deque

M, N, H = map(int, input().split())

box = []
q = deque()

for h in range(H):
    floor = []
    for i in range(N):
        row = list(map(int, input().split()))
        floor.append(row)

        for j in range(M):
            if row[j] == 1:
                q.append((h, i, j))

    box.append(floor)

h_1 = [1, -1, 0, 0, 0, 0]
x_1 = [0, 0, 1, -1, 0, 0]
y_1 = [0, 0, 0, 0, 1, -1]


while q:
    h, x, y = q.popleft()

    for k in range(6):
        h_2 = h + h_1[k]
        x_2 = x + x_1[k]
        y_2 = y + y_1[k]

        if 0 <= h_2 < H and 0 <= x_2 < N and 0 <= y_2 < M:
            if box[h_2][x_2][y_2] == 0:
                box[h_2][x_2][y_2] = box[h][x][y] + 1
                q.append((h_2, x_2, y_2))

day = 0

for h in range(H):
    for i in range(N):
        for j in range(M):
            if box[h][i][j] == 0:
                print(-1)
                quit()

            if box[h][i][j] > day:
                day = box[h][i][j]

print(day - 1)
        

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: