백준 #7569 토마토
문제 설명👩🏫
보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다. 하나의 토마토에 인접한 곳은 위, 아래, 왼쪽, 오른쪽, 앞, 뒤 여섯 방향에 있는 토마토를 의미한다. 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며, 토마토가 혼자 저절로 익는 경우는 없다고 가정한다. 철수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지 그 최소 일수를 구해라.
입력
5 3 2
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
출력
4
내 코드💻
import java.io.*;
import java.util.*;
public class Main {
static int [][][] tomato;
static int m,n,h;
static Queue<int[]> queue = new LinkedList<>();
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
StringTokenizer st = new StringTokenizer(str," ");
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
h = Integer.parseInt(st.nextToken());
tomato = new int[h][m][n];
for(int i=0;i<h;i++){
for(int j=0;j<m;j++){
str = br.readLine();
st = new StringTokenizer(str," ");
for(int k=0;k<n;k++){
tomato[i][j][k] = Integer.parseInt(st.nextToken());
if(tomato[i][j][k]==1) {
queue.offer(new int[]{i, j, k});
}
}
}
}
int answer = bfs();
if(answer == -1) {
System.out.println("-1");
}
else{
System.out.println(answer-1);
}
}
static int bfs(){
int[] dicZ = {1,-1,0,0,0,0};
int[] dicX = {0,0,0,0,1,-1};
int[] dicY = {0,0,1,-1,0,0};
int nowX,nowY,nowZ;
while(!queue.isEmpty()){
int[] tmp = queue.poll();
for(int i=0;i<6;i++){
nowZ = tmp[0] + dicZ[i];
nowX = tmp[1] + dicX[i];
nowY = tmp[2] + dicY[i];
if(checking(nowZ,nowX,nowY) && tomato[nowZ][nowX][nowY]==0){
tomato[nowZ][nowX][nowY] = tomato[tmp[0]][tmp[1]][tmp[2]]+1;
queue.offer(new int[]{nowZ,nowX,nowY});
}
}
}
int max = 0;
for(int i=0;i<h;i++){
for(int j=0;j<m;j++){
for(int k=0;k<n;k++){
if(tomato[i][j][k]==0) {
return -1;
}
else{
max = Math.max(max, tomato[i][j][k]);
}
}
}
}
return max;
}
static boolean checking(int z, int x, int y){
return (z>=0 && z<h && x>=0 && x<m && y>=0 && y<n);
}
}
설명💡
앞선 토마토 문제와 같은 유형이고, Z축만 추가하면 된다.
느낀 점 및 궁금한 점🍀
X,Y,Z축 지정할 때 순서가 조금 헷갈렸다.