철수의 토마토 농장에서는 토마토를 보관하는 큰 창고를 가지고 있다. 토마토는 아래의 그림과 같이 격자 모양 상자의 칸에 하나씩 넣어서 창고에 보관한다.
창고에 보관되는 토마토들 중에는 잘 익은 것도 있지만, 아직 익지 않은 토마토들도 있을 수 있다. 보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다. 하나의 토마토의 인접한 곳은 왼쪽, 오른쪽, 앞, 뒤 네 방향에 있는 토마토를 의미한다. 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며, 토마토가 혼자 저절로 익는 경우는 없다고 가정한다. 철수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지, 그 최소 일수를 알고 싶어 한다.
토마토를 창고에 보관하는 격자모양의 상자들의 크기와 익은 토마토들과 익지 않은 토마토들의 정보가 주어졌을 때, 며칠이 지나면 토마토들이 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라. 단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다.
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 상자에 담긴 토마토의 정보가 주어진다. 하나의 줄에는 상자 가로줄에 들어있는 토마토의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다.
토마토가 하나 이상 있는 경우만 입력으로 주어진다.
여러분은 토마토가 모두 익을 때까지의 최소 날짜를 출력해야 한다. 만약, 저장될 때부터 모든 토마토가 익어있는 상태이면 0을 출력해야 하고, 토마토가 모두 익지는 못하는 상황이면 -1을 출력해야 한다.
bfs로 시작점을 2개로 시작해야하는 것이 문제의 키포인트 였음
package baekjoon.dfsbfs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Q7576 {
static int N,M;
static int[][] box;
static int[][] visited;
public static void main(String[] args) throws IOException {
List<Location> startLocation =new ArrayList<>();
//입력
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
String[] strArr;
str = br.readLine();
strArr = str.split(" ");
M = Integer.parseInt(strArr[0]); //가로, 열
N = Integer.parseInt(strArr[1]); //세로, 행
box = new int[N][M];
visited = new int[N][M];
for (int i = 0; i < N; i++) {
str = br.readLine();
strArr = str.split(" ");
Arrays.fill(visited[i], 0);
for (int j = 0; j < M; j++) {
if(Integer.parseInt(strArr[j]) == 1) startLocation.add(new Location(i, j));
box[i][j] = Integer.parseInt(strArr[j]);
}
}
//모든토마토가 익은 상태면 0
if(isAllTomatoRiped()){
System.out.println(0);
} else{
int minDate = bfs(startLocation);
if(!isAllTomatoRiped()){ //토마토가 익지 못하는 상황 -1
System.out.println(-1);
} else{ //토마토가 익은 최소 날짜
System.out.println(minDate);
}
}
}
private static boolean isAllTomatoRiped() {
boolean flag = true;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if(box[i][j] == 0) flag = false;
}
}
return flag;
}
//시작점이 여러 개일 수 있는 bfs탐색
//상하좌우로 탐색하되 -1이면 탐색 못함
//visited배열을 bfs level을 담는데 씀
public static int bfs(List<Location> startLocation) {
int answer = 0;
List<Location> operator = new ArrayList<>();
operator.add(new Location(0, 1));
operator.add(new Location(0, -1));
operator.add(new Location(1, 0));
operator.add(new Location(-1, 0));
Queue<Location> q = new LinkedList<>();
for (Location location : startLocation) {
q.add(location);
visited[location.row][location.column] = 1;
}
while(!q.isEmpty()){
//큐에서 하나 뺌
Location curLocation = q.poll();
//마지막 요소인지 체크하여 그 값 return
for (int i = 0; i < 4; i++) {
int nextRow = curLocation.row + operator.get(i).row;
int nextColumn = curLocation.column + operator.get(i).column;
//상하좌우 살펴보고, 범위 내인지, 지나왔던 토마토인지,막힌 벽이 아닌지 체크
if((nextColumn>=0&&nextRow>=0&&nextColumn<M&&nextRow<N)
&& visited[nextRow][nextColumn] == 0
&& box[nextRow][nextColumn] != -1){
//큐에 넣어주고, visited에 level 표시, 박스에 익은 토마토 표시
visited[nextRow][nextColumn] = visited[curLocation.row][curLocation.column] + 1;
box[nextRow][nextColumn] = 1;
q.add(new Location(nextRow, nextColumn));
}
}
if(q.isEmpty()){
answer = visited[curLocation.row][curLocation.column];
}
}
return answer-1;
}
static class Location{
int row;
int column;
public Location(int row, int column) {
this.row = row;
this.column = column;
}
public Location() {
}
}
}