https://www.acmicpc.net/problem/7576
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.stream.Collectors;
public class Main {
static int[][] map;
static Queue<Point> queue;
public static int bfs() {
int[] dx = {-1, 0, 1, 0};
int[] dy = {0, -1, 0, 1};
while(!queue.isEmpty()) {
Point cur_point = queue.poll();
for(int i = 0; i < 4; i++) {
int cx = cur_point.x + dx[i];
int cy = cur_point.y + dy[i];
if(cx >= 0 && cx < map.length && cy >= 0 && cy < map[0].length) {
if(map[cx][cy] == 0) {
queue.offer(new Point(cx, cy));
map[cx][cy] = map[cur_point.x][cur_point.y] + 1;
}
}
}
}
int result = Integer.MIN_VALUE;
for(int i = 0; i < map.length; i++) {
for(int j = 0; j < map[i].length; j++) {
if(map[i][j] == 0) {
return -1;
}
result = Math.max(result, map[i][j]);
}
}
if(result == 1) {
return 0;
} else {
return result - 1;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String[] input = br.readLine().split(" ");
int col = Integer.parseInt(input[0]);
int row = Integer.parseInt(input[1]);
map = new int[row][col];
queue = new LinkedList<Point>();
for(int i = 0; i < row; i++) {
input = br.readLine().split(" ");
for(int j = 0; j < col; j++) {
map[i][j] = Integer.parseInt(input[j]);
if(map[i][j] == 1) {
queue.offer(new Point(i, j));
}
}
}
br.close();
bw.write(bfs() + "\n");
bw.flush();
bw.close();
}
public static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}
주어진 크기의 2차원 배열 map을 생성하고 map에 주어진 토마토들의 상태를 저장하는데 만약 해당 값이 1이라면, 즉 익은 토마토라면 해당 위치를 BFS 수행 시에 사용할 Queue에 넣습니다.
BFS 알고리즘을 이용하여 토마토 모두가 익을 때까지의 최소 날짜를 구합니다.
상하좌우의 좌표에 해당하는 dx, dy 배열을 생성하고 값을 초기화합니다.
Queue가 비워지기 전까지 반복문을 돌며 각각의 토마토가 익는 데에 걸리는 시간을 구합니다.
map 값 중 가장 큰 값, 즉 모든 토마토가 익는 데에 걸리는 시간을 나타내는 변수인 result를 생성하고 최소값으로 초기화합니다.
map의 모든 위치를 돌면서 0이 존재한다면, 즉 아직 익지 않은 토마토가 존재한다면 모든 토마토가 익을 수 없는 상황이므로 -1을 출력합니다. 그렇지 않다면 result의 값을 원래 result의 값과 현재 위치의 map 값 중 큰 것으로 변경합니다.
만약 result 값이 1이라면 모든 토마토가 이미 익어있는 상태이므로 0을 출력합니다.
그렇지 않다면 result 값을 출력합니다.