[Link] https://www.acmicpc.net/problem/7569
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//Position < int i, int j, int k , int step> =====> Memory exceed!!!
import java.util.*;
import java.io.*;
public class Main {
static int m, n, h;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int[][][] box;
Queue<Position> q = new LinkedList<>();
m = toi(line[0]);
n = toi(line[1]);
h = toi(line[2]);
box = new int[h][n][m];
int cnt = 0;
for(int i = 0; i < h; i++) {
for(int j = 0; j < n; j++) {
line = br.readLine().split(" ");
for(int k = 0; k < m; k++)
if(line[k].equals("1")) { //Can't use == (compares with array address)
box[i][j][k] = 1;
q.add(new Position(i, j, k));
} else if(line[k].equals("0")) cnt++;
else box[i][j][k] = -1;
}
}
print(bfs(box, q, cnt));
}
static class Position {
int i;
int j;
int k;
Position(int i, int j, int k) {
this.i = i;
this.j = j;
this.k = k;
}
}
static int bfs(int[][][] box, Queue<Position> q, int left) {
int[] di = new int[]{ 1, -1, 0, 0, 0, 0 };
int[] dj = new int[]{ 0, 0, 1, -1, 0, 0 };
int[] dk = new int[]{ 0, 0, 0 , 0, 1, -1};
int max = 0;
loop:
while(!q.isEmpty()) {
Position bottom = q.poll();
int I = bottom.i, J = bottom.j, K = bottom.k, step = box[I][J][K];
for(int i = 0; i < 6; i++) {
int si = di[i] + I, sj = dj[i] + J, sk = dk[i] + K;
if(0 <= si && si < h && 0 <= sj && sj < n && 0 <= sk && sk < m && box[si][sj][sk] == 0) {
box[si][sj][sk] = step + 1;
if(--left == 0) {
max = Math.max(step + 1, max);
break loop;
}
q.add(new Position(si, sj, sk));
}
}
max = Math.max(step, max);
}
return left == 0 ? max - 1 : -1;
}
static int toi(String s) { return Integer.parseInt(s); }
static <T> void print(T s) { System.out.print(s); }
static <T> void println(T s) { System.out.println(s); }
}