슈콩

[BOJ] 7569 토마토 본문

Algorithms/Baekjoon

[BOJ] 7569 토마토

shukong 2026. 1. 26. 22:11

[문제]

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

 

 

[소스 코드]

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

public class Solution {
	static int[] dr = {-1,1,0,0,0,0};
	static int[] dc = {0,0,-1,1,0,0};
	static int[] dz = {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());
		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<>();
		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());
					if(tomato[k][i][j]==1) {
						q.offer(new int[] {k,i,j});
					}
				}
			}
		}
		int result = 0;
		while(!q.isEmpty()) {
			boolean check = false;
			int size = q.size();
			for(int i=0;i<size;i++) {
				int[] curr = q.poll();
				for(int d=0;d<6;d++) {
					int nz = curr[0] + dz[d];
					int nr = curr[1] + dr[d];
					int nc = curr[2] + dc[d];
					if(nz<0 || nz>=h || nr<0 || nr>=n || nc<0 || nc>=m) continue;
					if(tomato[nz][nr][nc]==0) {
						check = true;
						q.offer(new int[] {nz,nr,nc});
						tomato[nz][nr][nc] = 1;
					}
				}
			}
			if(check) result++;
		}
		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) {
						System.out.println(-1);
						System.exit(0);
					}
				}
			}
		}
		System.out.println(result);
	}
}

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

[BOJ] 5014 스타트링크  (0) 2026.02.02
[BOJ] 1697 숨바꼭질  (0) 2026.01.28
[BOJ] 2664 촌수계산  (0) 2026.01.22
[BOJ] 2667 단지번호붙이기  (0) 2026.01.22
[BOJ] 2606 바이러스  (0) 2026.01.20