슈콩

[BOJ] 7569 토마토 본문

Algorithms/Baekjoon

[BOJ] 7569 토마토

shukong 2025. 11. 28. 21:02

 

 

[문제]

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

 

 

[소스 코드]

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

public class Main {
	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 Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int m = Integer.parseInt(st.nextToken());
		int n = Integer.parseInt(st.nextToken());
		int h = Integer.parseInt(st.nextToken());
		int[][][] tomato = new int[h][n][m];
		Queue<int[]> q = new LinkedList<>();
		int remain = 0;
		for(int i=0;i<h;i++) {
			for(int j=0;j<n;j++) {
				st = new StringTokenizer(br.readLine());
				for(int k=0;k<m;k++) {
					tomato[i][j][k] = Integer.parseInt(st.nextToken());
					if(tomato[i][j][k]==1) {
						q.offer(new int[] {i,j,k});
					}
					if(tomato[i][j][k]==0) remain++;
				}
			}
		}
		int result = 0;
		while(!q.isEmpty()) {
			int size = q.size();
			boolean check = false;
			for(int i=0;i<size;i++) {
				int[] curr = q.poll();
				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});
						check = true;
						remain--;
					}
				}
			}
			if(!check) break;
			result++;
		}
		if(remain!=0) System.out.println(-1);
		else System.out.println(result);
	}
}

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

[BOJ] 2468 안전 영역  (0) 2025.11.28
[BOJ] 5014 스타트링크  (0) 2025.11.28
[BOJ] 2644 촌수계산  (0) 2025.11.28
[BOJ] 2667 단지번호붙이기  (0) 2025.11.27
[BOJ] 2606 바이러스  (0) 2025.11.27