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

 

7569번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100,

www.acmicpc.net


7576번 문제의 3차원 배열 버전이다

푸는 방식은 동일하지만, 높이를 고려해야 하기때문에 배열을 3차원으로 선언하여 x,y 뿐만아니라 z까지 이동하는

방법으로 풀었다. static int N , M, H, 을 선언하고 int N, M, H 를 또 선언해줘서 괜한 시간 낭비를 했었다 ..


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 cnt = 0;
	static int map[][][];
	static int dx[] = { 1, 0, -1, 0, 0, 0 };
	static int dy[] = { 0, 1, 0, -1, 0, 0 };
	static int dz[] = { 0, 0, 0, 0, 1, -1 };
	static boolean visited[][][];
	static Queue<int[]> qu = new LinkedList<int[]>();

	public static void main(String agrs[]) 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());

		map = new int[H + 1][N + 1][M + 1];

		for (int i = 1; i <= H; i++) {
			for (int j = 1; j <= N; j++) {
				st = new StringTokenizer(br.readLine());
				for (int k = 1; k <= M; k++) {
					map[i][j][k] = Integer.parseInt(st.nextToken());

					if (map[i][j][k] == 1) {
						qu.add(new int[] { i, j, k });
					}
				}
			}
		}

		BFS();

		Loop1: for (int i = 1; i <= H; i++) {
			for (int j = 1; j <= N; j++) {
				for (int k = 1; k <= M; k++) {
					cnt = Math.max(map[i][j][k], cnt);

					if (map[i][j][k] == 0) {
						cnt = -1;
						break Loop1;
					}

				}
			}
		}
		if (cnt != -1)
			System.out.println(cnt - 1);
		else 
			System.out.println(cnt);
	
		

	}

	static void BFS() {

		while (!qu.isEmpty()) {
			int curH = qu.peek()[0];
			int curY = qu.peek()[1];
			int curX = qu.peek()[2];

			qu.poll();

			for (int i = 0; i < 6; i++) {
				int nh = curH + dz[i];
				int ny = curY + dy[i];
				int nx = curX + dx[i];

				if (nh <= 0 || ny <= 0 || nx <= 0 || nh > H || ny > N || nx > M)
					continue;

				if (map[nh][ny][nx] != 0)
					continue;

				qu.add(new int[] { nh, ny, nx });

				map[nh][ny][nx] = map[curH][curY][curX] + 1;

			}

		}
	}
}

 

+ Recent posts