[Gold V] 토마토 - 7569
성능 요약
메모리: 130692 KB, 시간: 636 ms
분류
너비 우선 탐색(bfs), 그래프 이론(graphs), 그래프 탐색(graph_traversal)
문제 설명
철수의 토마토 농장에서는 토마토를 보관하는 큰 창고를 가지고 있다. 토마토는 아래의 그림과 같이 격자모양 상자의 칸에 하나씩 넣은 다음, 상자들을 수직으로 쌓아 올려서 창고에 보관한다.
창고에 보관되는 토마토들 중에는 잘 익은 것도 있지만, 아직 익지 않은 토마토들도 있을 수 있다. 보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다. 하나의 토마토에 인접한 곳은 위, 아래, 왼쪽, 오른쪽, 앞, 뒤 여섯 방향에 있는 토마토를 의미한다. 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며, 토마토가 혼자 저절로 익는 경우는 없다고 가정한다. 철수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지 그 최소 일수를 알고 싶어 한다.
토마토를 창고에 보관하는 격자모양의 상자들의 크기와 익은 토마토들과 익지 않은 토마토들의 정보가 주어졌을 때, 며칠이 지나면 토마토들이 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라. 단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다.
입력
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100, 1 ≤ H ≤ 100 이다. 둘째 줄부터는 가장 밑의 상자부터 가장 위의 상자까지에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 하나의 상자에 담긴 토마토의 정보가 주어진다. 각 줄에는 상자 가로줄에 들어있는 토마토들의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0 은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다. 이러한 N개의 줄이 H번 반복하여 주어진다.
토마토가 하나 이상 있는 경우만 입력으로 주어진다.
출력
여러분은 토마토가 모두 익을 때까지 최소 며칠이 걸리는지를 계산해서 출력해야 한다. 만약, 저장될 때부터 모든 토마토가 익어있는 상태이면 0을 출력해야 하고, 토마토가 모두 익지는 못하는 상황이면 -1을 출력해야 한다.
풀이
처음에는 아무 생각 없이 삼차원 배열을 계속해서 탐색하면서 주변을 변화시킬 수 있는 경우 변화하도록 하였는데, 시간초과가 났다.
익은 토마토의 배열 값을 인접한 토마토의 값+1로 해서, 최대한 효율적으로 구현했다고 생각했는데, 삼차원 배열을 모두 탐색하는 것 자체가 시간이 많이 소요된 것 같다.
그래서 bfs로 바꿔 다시 구현하였다.
Tomato라는 static class를 만들어 n,m,h 좌표와 익은 날짜 day를 기록하였다.
static class Tomato {
int m;
int n;
int h;
int day;
public Tomato(int m, int n, int h, int day) {
this.m = m;
this.n = n;
this.h = h;
this.day = day;
}
}
초기에 queue에는 값이 1인 좌표를 새로운 Tomato 객체로 만들어 추가한다. 이때 day는 0으로 하였다.
그리고 while문에서 bfs를 수행하면서, 인접한 토마토의 값이 0일 경우 이를 바꾸고, 큐에 다시 추가한다.
큐가 빌 때까지 반복한 후, map에 아직 익지 않은 토마토가 있다면 0을 출력하고, 아니라면 cnt를 출력한다.
cnt는 while문 내부에서 tomato를 poll할 때마다 값을 업데이트해주었다.
가장 마지막까지 들어있는 토마토가 제일 늦게 익은 토마토이기 때문에 값을 비교하지 않고 덮어씌운다.
package BOJ.Gold.g5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class BOJ_7569_토마토 {
static class Tomato {
int m;
int n;
int h;
int day;
public Tomato(int m, int n, int h, int day) {
this.m = m;
this.n = n;
this.h = h;
this.day = day;
}
}
static int M, N, H;
static int[][][] map;
static int[] dn = {1, -1, 0, 0, 0, 0};
static int[] dm = {0, 0, 1, -1, 0, 0};
static int[] dh = {0, 0, 0, 0, 1, -1};
static int cntZero;
static Queue<Tomato> q = new LinkedList<>();
public static void main(String[] args) throws IOException {
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());
map = new int[M][N][H]; // 가로 M, 세로 N, 높이 H
cntZero = 0;
for (int h = 0; h < H; h++) {
for (int n = 0; n < N; n++) {
st = new StringTokenizer(br.readLine());
for (int m = 0; m < M; m++) {
map[m][n][h] = Integer.parseInt(st.nextToken());
if (map[m][n][h] == 1) {
q.add(new Tomato(m, n, h, 0));
}
}
}
}
int cnt = 0;
while (!q.isEmpty()) {
Tomato t = q.poll();
cnt = t.day;
change(t.m, t.n, t.h, t.day);
}
for (int h = 0; h < H; h++)
for (int n = 0; n < N; n++)
for (int m = 0; m < M; m++) {
if (map[m][n][h] == 0) {
System.out.println(-1);
return;
}
}
System.out.println(cnt);
}
static void change(int m, int n, int h, int cnt) {
for (int d = 0; d < 6; d++) {
int nm = m + dm[d];
int nn = n + dn[d];
int nh = h + dh[d];
if (nm >= 0 && nm < M && nn >= 0 && nn < N && nh >= 0 && nh < H && map[nm][nn][nh] == 0) {
map[nm][nn][nh] = cnt + 1;
q.add(new Tomato(nm, nn, nh, cnt + 1));
}
}
}
}
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 7570 - 줄 세우기 (자바 Java) (0) | 2022.12.14 |
---|---|
[백준] 2436 - 공약수 (자바 Java) (0) | 2022.12.13 |
[백준] 14891 - 톱니바퀴 (자바 Java) (0) | 2022.12.11 |
[백준] 1107 - 리모컨 (자바 Java) (0) | 2022.12.04 |
[백준] 5430 - AC (자바 Java) (1) | 2022.12.04 |