- 3차원인 점만 고려한다면, 전형적인 BFS 문제이다.
- 3차원 배열의 입력과 dz 배열을 유념하여 푼다.
import java.util.*;
public class Main {
static class Point{
int hei;
int wid;
int z;
public Point(int z ,int hei, int wid) {
this.z = z;
this.hei = hei;
this.wid = wid;
}
}
static int w,h,z;
static int[][][] graph;
static boolean[][][] ch;
static int[] dx = {-1,0,0,1,0,0};
static int[] dy = {0,1,-1,0,0,0};
static int[] dz = {0,0,0,0,-1,1};
static ArrayList<Point> init;
static int bfs(){
int L = 0;
Queue<Point> q = new LinkedList<>();
for(Point p : init) {
ch[p.z][p.hei][p.wid] = true;
q.offer(p);
}
while(!q.isEmpty()){
int len = q.size();
for(int i=0; i<len; ++i){
Point v = q.poll();
for(int j=0; j<dx.length; ++j){
int vhei = v.hei + dy[j];
int vwid = v.wid + dx[j];
int vz = v.z + dz[j];
if(vhei >= 0 && vwid >= 0 && vz >= 0
&& vhei < h && vwid < w && vz < z
&& !ch[vz][vhei][vwid] && graph[vz][vhei][vwid]==0){
ch[vz][vhei][vwid] = true;
graph[vz][vhei][vwid] = 1;
q.offer(new Point(vz, vhei, vwid));
}
}
}
L++;
}
return L;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
w = sc.nextInt();
h = sc.nextInt();
z = sc.nextInt();
graph = new int[z][h][w];
ch = new boolean[z][h][w];
for(int k = 0; k < z; ++k)
for (int i = 0; i < h; ++i)
for (int j = 0; j < w; ++j)
graph[k][i][j] = sc.nextInt();
init = new ArrayList<>();
for(int k = 0; k < z; ++k)
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
if(graph[k][i][j] == 1)
init.add(new Point(k,i,j));
}
}
int answer = bfs()-1;
boolean done = true;
for(int k = 0; k < z; ++k)
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
if(graph[k][i][j] == 0)
done = false;
}
}
if(done)
System.out.println(answer);
else
System.out.println(-1);
}
}