import java.util.*;
import java.io.*;
class Node {
public int x;
public int y;
public int z;
public int count;
public Node(int x, int y, int z , int count) {
this.x = x;
this.y = y;
this.z = z;
this.count = count;
}
}
class Main {
static int M, N, H;
static int[][][] tomato;
static boolean[][][] check;
static int dx[] = { 0 , 1 , 0 ,-1 , 0 , 0 };
static int dy[] = { -1 , 0 , 1 ,0 , 0 , 0 };
static int dz[] = { 0 , 0 , 0 ,0 , 1 , -1};
static int answer = 0;
static Queue<Node> queue = new LinkedList<>();
static int p = 0;
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int zerocount = 0;
M = Integer.parseInt(st.nextToken());
N = Integer.parseInt(st.nextToken());
H = Integer.parseInt(st.nextToken());
tomato = new int[N][M][H];
check = new boolean[N][M][H];
for (int h = 0; h < H; h++) {
for (int n = 0; n < N; n++) {
st = new StringTokenizer(br.readLine());
for (int m = 0; m < M; m++) {
tomato[n][m][h] = Integer.parseInt(st.nextToken());
if(tomato[n][m][h] == 0) {
zerocount++;
}
}
}
}
if(zerocount ==0) {
System.out.print(0);
return ;
}
for (int h = 0; h < H; h++) {
for (int n = 0; n < N; n++) {
for (int m = 0; m < M; m++) {
if (tomato[n][m][h] == 1 && !check[n][m][h]) {
queue.offer(new Node(m,n,h ,0)); //1 3 0
check[n][m][h] = true;
}
}
}
}
bfs();
if(zerocount == p) {
System.out.print(answer);
}else {
System.out.print(-1);
}
}
private static void bfs() {
while(!queue.isEmpty()) {
Node node = queue.poll();
int count = node.count;
answer = count;
for(int i = 0 ; i < 6 ; i++) {
int nextX = node.x + dx[i];
int nextY = node.y + dy[i];
int nextZ = node.z + dz[i];
if((nextX >= 0 && nextX < M ) && (nextY>=0 && nextY < N) && (nextZ >=0 && nextZ <H) && !check[nextY][nextX][nextZ] && tomato[nextY][nextX][nextZ] == 0) {
p++;
queue.offer(new Node(nextX,nextY,nextZ,count+1));
check[nextY][nextX][nextZ] = true;
tomato[nextY][nextX][nextZ] = 1;
// System.out.println(nextX + " " + nextY + " " + nextZ+ " " + (count+1));
}
}
}
}
}
3차원 배열로 풀이 높이값만 잘 처리하면 2차원 배열로도 가능할 것 같다.
0의 갯수가 0개면 바로 0을 리턴,
총 0의 갯수가 익은 토마토 갯수랑 다르면 -1을 리턴
나머지경우는 1을 전부 큐에 넣은 뒤 x,y,z,count 값을 가지는노드를 만들어서 풀이했다.
3차원배열 탐색은 처음이라 개떡같은코드가 완성돼서 내일 다시 풀어봐야겠다고 다짐