슈콩

[BOJ] 백준 7569 토마토 본문

Algorithms/Baekjoon

[BOJ] 백준 7569 토마토

shukong 2025. 9. 29. 23:39

[문제]

https://www.acmicpc.net/problem/7569

 

 

[소스 코드]

import java.io.*;
import java.util.*;

public class Main {
	static int m,n,h,result = 0;
	static int[][][] tomato;
	static int[] dh = {1,-1,0,0,0,0};
	static int[] dr = {0,0,-1,1,0,0};
	static int[] dc = {0,0,0,0,-1,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());
		h = Integer.parseInt(st.nextToken());
		tomato = new int[h][n][m];
		for(int k=0;k<h;k++) {
			for(int i=0;i<n;i++) {
				st = new StringTokenizer(br.readLine());
				for(int j=0;j<m;j++) {
					tomato[k][i][j] = Integer.parseInt(st.nextToken());
				}
			}
		}
		bfs();
		if(possible()) System.out.println(result);
		else System.out.println(-1);
	}
	private static void bfs() {
		Queue<int[]> q = new LinkedList<>();
		for(int k=0;k<h;k++) {
			for(int i=0;i<n;i++) {
				for(int j=0;j<m;j++) {
					if(tomato[k][i][j]==1) {
						q.offer(new int[] {k,i,j,0});
					}
				}
			}
		}    
		while(!q.isEmpty()) {
			int[] curr = q.poll();
			result = Math.max(result, curr[3]);
			
			for(int d=0;d<6;d++) {
				int nh = curr[0] + dh[d];
				int nr = curr[1] + dr[d];
				int nc = curr[2] + dc[d];
				if(nh<0 || nh>=h || nr<0 || nr>=n || nc<0 || nc>=m) continue;
				if(tomato[nh][nr][nc]==0) {
					tomato[nh][nr][nc] = 1;
					q.offer(new int[] {nh,nr,nc,curr[3]+1});
				}
			}
		}
	}
	private static boolean possible() {
		for(int k=0;k<h;k++) {
			for(int i=0;i<n;i++) {
				for(int j=0;j<m;j++) {
					if(tomato[k][i][j]==0) return false;
				}
			}
		}
		return true;
	}
}

'Algorithms > Baekjoon' 카테고리의 다른 글

[BOJ] 백준 5014 스타트링크  (0) 2025.09.30
[BOJ] 백준 1697 숨바꼭질  (0) 2025.09.30
[BOJ] 백준 2644 촌수계산  (0) 2025.09.29
[BOJ] 백준 2667 단지번호붙이기  (0) 2025.09.29
[BOJ] 백준 2606 바이러스  (0) 2025.09.29