• Home
  • About
    • Ryureka Moment photo

      Ryureka

      Sin Prisa, Sin Pausa

    • About Me
    • Facebook
    • Github
    • Youtube
  • Projects
  • Posts
    • Posts
    • ProblemSolvings
    • Tags
    • Blog
    • Examples
  • ProblemSolving
    • ProblemSolving
    • BOJ
    • Programmers
    • SWEA
    • LeetCode
  • FrontEnd
    • FrontEnd
    • HTML
  • BackEnd
    • BackEnd
    • Server
      • Server
      • Spring
      • NodeJS
    • DataBase
      • DataBase
      • MySQL
      • MongoDB
  • Programming
    • Programming
    • Java
    • JS
    • Python
    • CleanCode
  • ComputerScience
    • DataStructure
    • Algorithm

[BOJ] 7569. 토마토

15 Apr 2026

Reading time ~1 minute

  • 풀이

풀이

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int M=sc.nextInt();
		int N=sc.nextInt();
		int H=sc.nextInt();
		
		int[] dx= {0,0,0,0,-1,1};
		int[] dy= {0,0,-1,1,0,0};
		int[] dz= {-1,1,0,0,0,0};
		
		Queue<Point> q=new LinkedList<Point>();
		int[][][] arr=new int [H][N][M];
		int[][][] dist=new int [H][N][M];
		for(int i=0;i<H;i++) {
			for(int j=0;j<N;j++) {
				Arrays.fill(dist[i][j], -1);
			}
		}
		
		for (int i = 0; i < H; i++) {
			for(int j = 0;j < N; j++) {
				for (int k = 0; k < M; k++) {
					arr[i][j][k]=sc.nextInt();
					if(arr[i][j][k]==1) {
						q.add(new Point(i,j,k));
						dist[i][j][k]=1;
					}
				}
			}
		}
		
		while(!q.isEmpty()) {
			Point p=q.poll();
			for(int i=0;i<6;i++) {
				int nx=p.x+dx[i];
				int ny=p.y+dy[i];
				int nz=p.z+dz[i];
				if(nx>=0 && nx < M && ny>=0 && ny < N && nz>=0 && nz < H 
				&& dist[nz][ny][nx]==-1 && arr[nz][ny][nx]==0) {
					q.add(new Point(nz,ny,nx));
					dist[nz][ny][nx]=dist[p.z][p.y][p.x]+1;
					arr[nz][ny][nx]=1;
				}
			}
		}
		
		
		int max=Integer.MIN_VALUE;
		boolean flag=true;
		for(int i=0;i<H;i++) {
			for(int j=0;j<N;j++) {
				for(int k=0;k<M;k++) {
					if(arr[i][j][k]==0) {
						flag=false; break;
					}
					if(dist[i][j][k]!=-1 && max<dist[i][j][k]) {
						max=dist[i][j][k];
					}
				}
			}
		}
		if(flag) {
			System.out.println(max-1);
		}else {
			System.out.println("-1");
		}
	}//Main End
	
	static class Point{
		int z,y,x;
		Point(int z,int y,int x){
			this.z=z;
			this.y=y;
			this.x=x;
		}
	}
}


BFS Share