[BFS] 7569. 토마토 - G5

GIGI·2022년 10월 27일

BOJ in Java

목록 보기
7/18
post-thumbnail

package boj_7569_토마토_g5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {
	static int M, N, H;
	static int[][][] box;
	static boolean[][][] visit;
	static int[] dx = { 0, 0, -1, 1, 0, 0 }, dy = { -1, 1, 0, 0, 0, 0 }, dz = { 0, 0, 0, 0, -1, 1 };
	static Queue<Point> queue;

	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());
		box = new int[M][N][H];
		visit = new boolean[M][N][H];
		queue = new LinkedList<>();
		boolean isZeroHere = false;
		for (int h = 0; h < H; h++) {
			for (int n = 0; n < N; n++) {
				st = new StringTokenizer(br.readLine());
				for (int m = 0; m < M; m++) {
					box[m][n][h] = Integer.parseInt(st.nextToken());
					if (box[m][n][h] == 1) {
						queue.offer(new Point(m, n, h));
						visit[m][n][h] = true;
					}
					if (box[m][n][h] == 0) {
						isZeroHere = true;
					}
				}
			}
		} // 입력 끝
			// print();
		if (!isZeroHere) {
			System.out.println(0);
			return;
		}
		if (isZeroHere) {
			ripenTomato();
			int days = cntDays();
			System.out.println(days);
		}
	}

	static int cntDays() {
		int maxCnt = 0;
		for (int h = 0; h < H; h++) {
			for (int n = 0; n < N; n++) {
				for (int m = 0; m < M; m++) {
					if (box[m][n][h] == 0) {
						return -1;
					} else if (box[m][n][h] > maxCnt) {
						maxCnt = box[m][n][h];
					}

				}
			}
		}
		return maxCnt-1;
	}

	static void ripenTomato() {
		while (!queue.isEmpty()) {
			Point p = queue.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 && ny >= 0 && nz >= 0 && nx < M && ny < N && nz < H && !visit[nx][ny][nz]) {
					if (box[nx][ny][nz] == -1) {
						visit[nx][ny][nz] = true;
						continue;
					} else {
						box[nx][ny][nz] = box[p.x][p.y][p.z] + 1;
						queue.offer(new Point(nx, ny, nz));
						visit[nx][ny][nz] = true;
					}
				}
			}
		}
		//print();
	}

	static void print() {
		for (int h = 0; h < H; h++) {
			for (int n = 0; n < N; n++) {
				for (int m = 0; m < M; m++) {
					System.out.print(box[m][n][h] + " ");
				}
				System.out.println();
			}
		}
	}
}

class Point {
	int x;
	int y;
	int z;

	Point(int x, int y, int z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}
}

그전에 풀었던 토마토 문제가 3차원으로 바뀐 것 밖에 다른게 없었다.
하지만 모든 토마토가 썩을 때까지 날짜를 세기 위해 box상의 토마토의 값을 점차 늘려준다는 아이디어는 계속 가져와야하는 것 같다
그것만 알면 어려울 것 없는 문제.

profile
이제 누구도 날 막을 수 없다!!!!!!!!!!

0개의 댓글