https://www.acmicpc.net/problem/7569
정답률 42.608%
철수의 토마토 농장에서는 토마토를 보관하는 큰 창고를 가지고 있다. 토마토는 아래의 그림과 같이 격자모양 상자의 칸에 하나씩 넣은 다음, 상자들을 수직으로 쌓아 올려서 창고에 보관한다.
창고에 보관되는 토마토들 중에는 잘 익은 것도 있지만, 아직 익지 않은 토마토들도 있을 수 있다. 보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다. 하나의 토마토에 인접한 곳은 위, 아래, 왼쪽, 오른쪽, 앞, 뒤 여섯 방향에 있는 토마토를 의미한다. 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며, 토마토가 혼자 저절로 익는 경우는 없다고 가정한다. 철수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지 그 최소 일수를 알고 싶어 한다.
토마토를 창고에 보관하는 격자모양의 상자들의 크기와 익은 토마토들과 익지 않은 토마토들의 정보가 주어졌을 때, 며칠이 지나면 토마토들이 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라. 단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다.
5 3 1
0 -1 0 0 0
-1 -1 0 1 1
0 0 0 1 1
-1
2차원 토마토 문제와 동일하며 3차원으로만 변경됐다.
최소 일수는 결국 최소 이동거리를 거리를 구하는 것이므로 BFS를 이용한다. 처음에 익은 토마토가 여러 개일 수 있으니 BFS 탐색 전에 배열에서 1을 탐색하여 큐에 삽입한다.
//백준
public class Main {
static int X, Y, Z;
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[][][] tomatoes;
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("src/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
X = Integer.parseInt(st.nextToken());
Y = Integer.parseInt(st.nextToken());
Z = Integer.parseInt(st.nextToken());
/*
1 -> 익은 토마토
0 -> 안익은 토마토
-1 -> 빈 칸
*/
tomatoes = new int[Z][Y][X];
for (int z = 0; z < Z; z++) {
for (int i = 0; i < Y; i++) {
tomatoes[z][i] = Arrays.stream(br.readLine().split(" "))
.mapToInt(Integer::parseInt)
.toArray();
}
}
//이미 다 익은 경우
boolean alreadyRipe = Arrays.stream(tomatoes)
.flatMap(Arrays::stream)
.flatMapToInt(Arrays::stream)
.noneMatch(i -> i == 0);
if (alreadyRipe) {
System.out.println(0);
return;
}
bfs();
//안익은 토마토가 존재할 경우
boolean existsUnripe = Arrays.stream(tomatoes)
.flatMap(Arrays::stream)
.flatMapToInt(Arrays::stream)
.anyMatch(i -> i == 0);
if (existsUnripe) {
System.out.println(-1);
return;
}
int result = Arrays.stream(tomatoes)
.flatMap(Arrays::stream)
.flatMapToInt(Arrays::stream)
.max()
.orElseThrow();
System.out.println(result - 1);
}
static void bfs() {
Queue<int[]> queue = new LinkedList<>();
for (int z = 0; z < Z; z++) {
for (int y = 0; y < Y; y++) {
for (int x = 0; x < X; x++) {
if (tomatoes[z][y][x] == 1) {
queue.add(new int[]{x, y, z});
}
}
}
}
while (!queue.isEmpty()) {
int[] cur = queue.poll();
int curX = cur[0];
int curY = cur[1];
int curZ = cur[2];
for (int i = 0; i < 6; i++) {
int nextX = curX + dx[i];
int nextY = curY + dy[i];
int nextZ = curZ + dz[i];
if (nextX < 0 || nextX >= X
|| nextY < 0 || nextY >= Y
|| nextZ < 0 || nextZ >= Z) {
continue;
}
if (tomatoes[nextZ][nextY][nextX] == 0) {
queue.add(new int[]{nextX, nextY, nextZ});
tomatoes[nextZ][nextY][nextX] = tomatoes[curZ][curY][curX] + 1;
}
}
}
}
}