풀었던 문제를 다시 풀어보았다. 처음 풀었을 때와 코드가 조금 다르지만, 빠르게 풀 수 있었다. 요구사항이 조금 더 복잡한 문제를 풀어봐야겠다. 또한 행렬 전체를 검사해야 할 때, count를 이용할 수 있다는 아이디어도 기억해 두어야겠다.
public class P7569_2 {
static class Point {
int m, n, h;
public Point(int m, int n, int h) {
this.m = m;
this.n = n;
this.h = h;
}
}
static int m, n, h, box[][][], notRipe;
static Queue <Point> q = new LinkedList<>();
static int dx[] = {1, -1, 0, 0, 0, 0};
static int dy[] = {0, 0, 1, -1, 0, 0};
static int dz[] = {0, 0, 0, 0, 1, -1};
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
m = Integer.parseInt(st.nextToken());
n = Integer.parseInt(st.nextToken());
h = Integer.parseInt(st.nextToken());
box = new int[h][n][m];
notRipe = 0;
for(int i=0; i<h; i++) {
for(int j=0; j<n; j++) {
st = new StringTokenizer(br.readLine());
for(int k=0; k<m; k++) {
box[i][j][k] = Integer.parseInt(st.nextToken());
if(box[i][j][k] == 1)
q.add(new Point(k, j, i));
if(box[i][j][k] == 0)
notRipe++;
}
}
}
// 익지 않은 토마토가 없는 경우 0, 있는 경우 카운트 시작
if(notRipe == 0) System.out.println(0);
else bfs();
}
public static void bfs() {
int day = -1;
while(!q.isEmpty()) {
int size = q.size();
for(int i=0; i<size; i++) {
Point p = q.poll();
for(int j=0; j<dx.length; j++) {
int x = p.m + dx[j];
int y = p.n + dy[j];
int z = p.h + dz[j];
if(x >= 0 && x < m && y >= 0 && y < n && z >= 0 && z < h && box[z][y][x] == 0) {
q.add(new Point(x, y, z));
box[z][y][x] = 1;
notRipe--;
}
}
}
day++;
}
if(notRipe == 0) System.out.println(day);
else System.out.println(-1);
}
}
// 문제 review
public class P7569_r {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
Queue <int[]> q = new LinkedList<>();
int m = Integer.parseInt(st.nextToken());
int n = Integer.parseInt(st.nextToken());
int h = Integer.parseInt(st.nextToken());
int[][][] box = new int[h][n][m];
int total = 0;
for(int i=0; i<h; i++) {
for(int j=0; j<n; j++) {
st = new StringTokenizer(br.readLine());
for(int k=0; k<m; k++) {
box[i][j][k] = Integer.parseInt(st.nextToken());
if(box[i][j][k] != -1) {
total++;
if(box[i][j][k] == 1) {
q.add(new int[] {i, j, k});
}
}
}
}
}
int[] dx = {1,-1,0,0,0,0};
int[] dy = {0,0,1,-1,0,0};
int[] dz = {0,0,0,0,1,-1};
int cnt = -1;
while(!q.isEmpty()) {
int size = q.size();
for(int i=0; i<size; i++) {
int[] curr = q.poll();
for(int j=0; j<6; j++) {
int z = dz[j] + curr[0];
int y = dy[j] + curr[1];
int x = dx[j] + curr[2];
if(x < 0 || x >= m || y < 0 || y >= n || z < 0 || z >= h) continue;
if(box[z][y][x] == 0) {
box[z][y][x] = 1;
q.add(new int[] {z,y,x});
}
}
total--;
}
cnt++;
}
if(total == 0) System.out.println(cnt);
else System.out.println(-1);
}
}