문제 분석

- BOJ 7576 토마토 문제의 2차원 배열을 3차원으로 변경하면 된다.

(* 7576번 문제 분석/문제 풀이 참고)

 

 

문제 풀이

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 {
	private static int N, M, H, ans;
	private static int[][][] map;
	private static int[] dr = { -1, 1, 0, 0, 0, 0 }; // 좌우상하앞뒤
	private static int[] dc = { 0, 0, -1, 1, 0, 0 };
	private static int[] dz = { 0, 0, 0, 0, -1, 1 };

	public static void main(String[] args) throws Exception {
		input();
	}// main

	static void input() throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;

		st = new StringTokenizer(br.readLine());
		M = Integer.parseInt(st.nextToken());
		N = Integer.parseInt(st.nextToken());
		H = Integer.parseInt(st.nextToken());
		map = 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++) {
					map[k][i][j] = Integer.parseInt(st.nextToken());
				}
			}
		} // for
		if (bfs()) {
			System.out.println(ans);
		} else {
			System.out.println("-1");
		}
	}// input

	static boolean bfs() {

		Queue<Point> 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 (map[k][i][j] == 1) {
						q.add(new Point(i, j, k, 0));
					}
				}
			}
		}

		while (!q.isEmpty()) {
			Point cur = q.poll();
			int curX = cur.x;
			int curY = cur.y;
			int curZ = cur.z;
			ans = cur.day;

			for (int d = 0; d < 6; d++) { // 상하좌우
				int nx = curX + dr[d];
				int ny = curY + dc[d];
				int nz = curZ + dz[d];
				if (nz >= 0 && nx >= 0 && ny >= 0 && nz < H && nx < N && ny < M) {
					if (map[nz][nx][ny] == 0) {
						map[nz][nx][ny] = 1;
						q.add(new Point(nx, ny, nz, ans + 1));
					}

				}
			}
		}

		// 상태 체크
		return chk();
	}// bfs

	private static boolean chk() {
		for (int i = 0; i < H; i++) {
			for (int j = 0; j < N; j++) {
				for (int k = 0; k < M; k++) {
					if (map[i][j][k] == 0) {
						return false;
					}
				}
			}
		}
		return true;
	}// chk

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

		Point(int x, int y, int z, int day) {
			this.x = x;
			this.y = y;
			this.z = z;
			this.day = day;
		}
	}// Point-class-end

}// class-end

'Algorithm > BOJ' 카테고리의 다른 글

BOJ 7562 나이트의이동  (0) 2021.03.22
BOJ 2178 미로 탐색  (0) 2021.03.19
BOJ 7576 토마토  (0) 2021.03.17
BOJ 2468 안전영역  (0) 2021.03.17
BOJ 2667 단지번호붙이기  (0) 2021.03.16