
2024년 8월에 쓴 풀이를 옮기면서 출력 조건 설명을 바로잡고 예제 실행 결과를 더했다.
문제
M x N 크기의 상자를 H층으로 쌓아 둔 창고가 있다. 익은 토마토(1)는 하루가 지나면 위, 아래, 앞, 뒤, 왼쪽, 오른쪽에 붙어 있는 익지 않은 토마토(0)를 익게 만들고, -1은 토마토가 없는 칸이다. 토마토가 모두 익을 때까지 최소 며칠이 걸리는지 출력하는데, 처음부터 다 익어 있으면 0, 다 익지 못하면 -1을 출력한다.

문제풀이
전형적인 BFS 문제다. 처음부터 익어 있는 토마토를 모두 Queue에 담고, 위층, 아래층, 상, 하, 좌, 우 여섯 방향으로 퍼져 나가며 탐색하면 된다. 아래 조건을 주의해야 한다.
- 처음부터 다 익어 있으면 0, 다 익지 못하면 -1을 출력한다. (끝까지 익지 못하는 토마토가 있는 입력도 나온다.)
- 상자의 일부 칸에는 토마토가 없을 수 있다.
큐에 넣을 때 며칠째에 익었는지(d)를 같이 넣어 두고, 새로 익힐 때마다 d + 1과 지금까지의 최댓값을 비교한다. BFS가 끝난 뒤에도 0인 칸이 남아 있으면 -1을 출력한다. 처음부터 다 익어 있으면 새로 익히는 토마토가 없어서 res가 0 그대로 출력된다.
소스코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static int M, N, H, res;
public static int[][][] map;
public static int[] dx = {0, 0, 0, 0, -1, 1};
public static int[] dy = {0, 0, -1, 1, 0, 0};
public static int[] dh = {-1, 1, 0, 0, 0, 0};
public static Queue<Tomato> q = new LinkedList<>();
public static class Tomato {
int x, y, h, d;
public Tomato(int h, int y, int x, int d) {
this.x = x;
this.y = y;
this.h = h;
this.d = d;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] param = br.readLine().split(" ");
M = Integer.parseInt(param[0]);
N = Integer.parseInt(param[1]);
H = Integer.parseInt(param[2]);
map = new int[H][N][M];
for (int i = H - 1; i >= 0; i--) {
for (int j = 0; j < N; j++) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
for (int k = 0; k < M; k++) {
map[i][j][k] = Integer.parseInt(st.nextToken());
// 처음부터 익어 있는 토마토를 모두 큐에 넣고 시작한다
if (map[i][j][k] == 1) q.add(new Tomato(i, j, k, 0));
}
}
}
while (!q.isEmpty()) {
Tomato t = q.poll();
for (int i = 0; i < 6; i++) {
int h = t.h + dh[i];
int y = t.y + dy[i];
int x = t.x + dx[i];
if (h < 0 || h >= H || x < 0 || x >= M || y < 0 || y >= N
|| map[h][y][x] == 1 || map[h][y][x] == -1) continue;
map[h][y][x] = 1;
res = Math.max(t.d + 1, res);
q.add(new Tomato(h, y, x, t.d + 1));
}
}
// 익지 못한 토마토가 하나라도 남으면 -1
for (int i = 0; i < H; i++) {
for (int j = 0; j < N; j++) {
for (int k = 0; k < M; k++) {
if (map[i][j][k] == 0) {
System.out.println(-1);
System.exit(0);
}
}
}
}
System.out.println(res);
}
}
검증
BOJ 예제 3개를 로컬 Java 22에서 돌렸고 모두 기대 출력과 같았다. 세 예제가 출력 조건 세 가지를 하나씩 보여 준다.
| 예제 | 출력 | 상황 |
| 1 | -1 | -1 칸에 막혀 끝까지 익지 못하는 토마토가 남는다 |
| 2 | 4 | 4일째에 모두 익는다 |
| 3 | 0 | 처음부터 모든 토마토가 익어 있다 |
참고
- BOJ 7569 토마토
- BOJ 7576 토마토 (상자가 한 층인 2차원 버전)
- 위키백과: 너비 우선 탐색
댓글
GitHub 계정으로 로그인하면 댓글과 공감을 남길 수 있습니다.