[백준] 7576. 토마토 (자바 JAVA)
문제
철수의 토마토 농장에서는 토마토를 보관하는 큰 창고를 가지고 있다. 토마토는 아래의 그림과 같이 격자 모양 상자의 칸에 하나씩 넣어서 창고에 보관한다.

창고에 보관되는 토마토들 중에는 잘 익은 것도 있지만, 아직 익지 않은 토마토들도 있을 수 있다. 보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다. 하나의 토마토의 인접한 곳은 왼쪽, 오른쪽, 앞, 뒤 네 방향에 있는 토마토를 의미한다. 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며, 토마토가 혼자 저절로 익는 경우는 없다고 가정한다. 철수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지, 그 최소 일수를 알고 싶어 한다.
토마토를 창고에 보관하는 격자모양의 상자들의 크기와 익은 토마토들과 익지 않은 토마토들의 정보가 주어졌을 때, 며칠이 지나면 토마토들이 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라. 단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다.
입력
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다.
토마토가 하나 이상 있는 경우만 입력으로 주어진다.
출력
여러분은 토마토가 모두 익을 때까지의 최소 날짜를 출력해야 한다. 만약, 저장될 때부터 모든 토마토가 익어있는 상태이면 0을 출력해야 하고, 토마토가 모두 익지는 못하는 상황이면 -1을 출력해야 한다.
예제 입력 1
6 4
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 1
예제 출력 1
8
예제 입력 2
6 4
0 -1 0 0 0 0
-1 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 1
예제 출력 2
-1
예제 입력 3
6 4
1 -1 0 0 0 0
0 -1 0 0 0 0
0 0 0 0 -1 0
0 0 0 0 -1 1
예제 출력 3
6
예제 입력 4
5 5
-1 1 0 0 0
0 -1 -1 -1 0
0 -1 -1 -1 0
0 -1 -1 -1 0
0 0 0 0 0
예제 출력 4
14
예제 입력 5
2 2
1 -1
-1 1
예제 출력 5
0
접근 방법 🧐
이 문제에서는 동시에 여러 방향으로 익어가는 과정을 구현해야 하므로 DFS로 푸는 것은 부적절하다.
그래서 BFS로 접근해서 풀었지만, 2가지 풀이 방법이 있다.
우선 공통점으로는
초기에 토마토가 모두 익은 상태인지를 체크한다.
그리고 q에 익은 토마토를 넣고, q에 담겨져있는 현재 익은 토마토의 해당 위치를 꺼내서 상하좌우를 체크한다.
아직 익지 않은 토마토가 있으면 토마토의 위치를 큐에 추가한다.
q가 비어져서 토마토를 다 익게 만들었다면
토마토 전체를 다시 돌면서 익지 않은 토마토가 있으면 -1을 출력, 없으면 익을 때까지 걸린 날짜를 출력한다.
내가 쓴 코드 ✍️
코드 1과 코드 2는 일수(days)를 저장하고 관리하는 방식에 있어서 큰 차이가 있다.
코드 1
토마토 좌표에 days를 따로 저장해서 처음 익은 토마토는 0부터 시작한다.
마지막으로 q에서 나온 days 값을 그대로 출력하면 토마토가 익는 데까지 최소 일자가 출력된다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
private static class Point {
int x, y, days;
public Point(int x, int y, int days) {
this.x = x;
this.y = y;
this.days = days;
}
}
private static int M, N, days;
private static int[] dx = { -1, 0 , 1, 0 };
private static int[] dy = { 0, 1, 0, -1 };
private static int[][] map;
private static Queue<Point> q;
private static void BFS(int x, int y) {
while (!q.isEmpty()) {
Point now = q.poll();
days = now.days;
for (int d = 0; d < 4; d++) {
int nx = now.x + dx[d];
int ny = now.y + dy[d];
if (checkOutOfRange(nx, ny) || map[nx][ny] == -1) continue;
if (map[nx][ny] == 0) {
map[nx][ny] = 1;
q.offer(new Point(nx, ny, days + 1));
}
}
}
}
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());
map = new int[N][M];
boolean isAlreadyAllRipen = true;
q = new LinkedList<>();
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < M; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
if (map[i][j] == 1) {
q.offer(new Point(i, j, 0));
} else if (map[i][j] == 0) { // 저장할 때부터 모든 토마토가 익어있는 상태이면 0을 출력
isAlreadyAllRipen = false;
}
}
}
if (isAlreadyAllRipen) {
System.out.println(0);
return;
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] == 1) {
BFS(i, j);
}
}
}
if (checkNotAllRipen()) { // 토마토가 모두 익지는 못하는 상황이면 -1을 출력
System.out.println(-1);
return;
}
if (days == 0) {
System.out.println(0);
} else {
System.out.println(days);
}
}
private static boolean checkNotAllRipen() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] == 0) {
return true;
}
}
}
return false;
}
private static boolean checkOutOfRange(int x, int y) {
return x < 0 || x >= N || y < 0 || y >= M;
}
}
코드 2
기존 map[x][y] 값을 기반으로 +1을 하면서 익은 날짜를 업데이트한다.
따라서 days의 최댓값은 마지막 날의 map 값이므로, 1부터 시작한 초기값을 보정하기 위해 마지막에 days - 1을 해서 출력해야 한다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
private static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
private static int M, N, days;
private static int[] dx = { -1, 0 , 1, 0 };
private static int[] dy = { 0, 1, 0, -1 };
private static int[][] map;
private static Queue<Point> q;
private static void BFS(int x, int y) {
q.offer(new Point(x, y));
while (!q.isEmpty()) {
Point now = q.poll();
for (int d = 0; d < 4; d++) {
int nx = now.x + dx[d];
int ny = now.y + dy[d];
if (checkOutOfRange(nx, ny) || map[nx][ny] == -1) continue;
if (map[nx][ny] == 0) {
map[nx][ny] = map[now.x][now.y] + 1;
q.offer(new Point(nx, ny));
}
}
}
}
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());
map = new int[N][M];
boolean isAlreadyAllRipen = true;
q = new LinkedList<>();
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < M; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
if (map[i][j] == 1) {
q.offer(new Point(i, j));
} else if (map[i][j] == 0) { // 저장할 때부터 모든 토마토가 익어있는 상태이면 0을 출력
isAlreadyAllRipen = false;
}
}
}
if (isAlreadyAllRipen) {
System.out.println(0);
return;
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] == 1) {
BFS(i, j);
}
}
}
if (checkNotAllRipen()) { // 토마토가 모두 익지는 못하는 상황이면 -1을 출력
System.out.println(-1);
return;
}
if (days == 1) {
System.out.println(0);
} else {
System.out.println(days - 1);
}
}
private static boolean checkNotAllRipen() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] == 0) {
return true;
}
days = Math.max(days, map[i][j]);
}
}
return false;
}
private static boolean checkOutOfRange(int x, int y) {
return x < 0 || x >= N || y < 0 || y >= M;
}
}
개인적으로 나는 코드 1을 더 선호한다 :)