땀두 블로그

[백준] 7569번 - 토마토 본문

알고리즘/백준

[백준] 7569번 - 토마토

땀두 2022. 3. 23. 07:58

 

 

 

위 링크에 있는 토마토가 X * Y의 배열이었다면 이번엔 X*Y*Z로 3차원으로 증가를 한 문제이다. 문제자체는 같은 방식으로 해결하지만, 3차원이라 인덱스를 잡는 부분에서 헷갈려 오래걸린것 같다.

 

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

class Node7569 {
	// x = 높이 y= 가로 z = 세로
	int x;
	int y;
	int z;
	Node7569(int x, int y, int z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}
}

public class p7569 {
	public static int[][][] ary;
	public static int a;
	public static int b;
	public static int h;
	public static int[] nx = { 0, 0, 0, 0, 1, -1 };
	public static int[] ny = { 0, 0, 1, -1, 0, 0 };
	public static int[] nz = { 1, -1, 0, 0, 0, 0 };
	public static Queue<Node7569> q;

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());

		a = Integer.parseInt(st.nextToken());
		b = Integer.parseInt(st.nextToken());
		h = Integer.parseInt(st.nextToken());

		ary = new int[h + 1][b + 1][a + 1];

		q = new LinkedList<Node7569>();

		for (int i = 1; i <= h; i++) {
			for (int j = 1; j <= b; j++) {
				st = new StringTokenizer(br.readLine());
				for (int k = 1; k <= a; k++) {
					ary[i][j][k] = Integer.parseInt(st.nextToken());

					if (ary[i][j][k] == 1) {
						q.add(new Node7569(i, j, k));
					}
				}
			}
		}
		bfs();

		int rst = Integer.MIN_VALUE;

		for (int i = 1; i <= h; i++) {
			for (int j = 1; j <= b; j++) {
				for (int k = 1; k <= a; k++) {
					if (ary[i][j][k] == 0) {
						System.out.println(-1);
						return;
					}
					rst = Math.max(rst, ary[i][j][k]);
				}
			}
		}
		System.out.println(rst-1);
		return;
	}

	public static void bfs() {
		while (!q.isEmpty()) {
			Node7569 n = q.poll();

			int x = n.x;
			int y = n.y;
			int z = n.z;
			
			for (int i = 0; i < 6; i++) {
				int xx = x + nx[i];
				int yy = y + ny[i];
				int zz = z + nz[i];

				if (xx > 0 && xx <= h && yy > 0 && yy <= b && zz > 0 && zz <= a) {	
					if (ary[xx][yy][zz] == 0) {
						q.add(new Node7569(xx, yy, zz));
						ary[xx][yy][zz] = ary[x][y][z] + 1;
					}
				}
			}
		}
	}
}
 

 

 

'알고리즘 > 백준' 카테고리의 다른 글

[백준] 6064번 - 카잉 달력  (0) 2022.03.23
[백준] 1992번 - 쿼드트리  (0) 2022.03.23
[백준] 11656번 - 접미사 배열  (0) 2022.03.23
[백준] 3048번 - 개미  (0) 2022.03.22
[백준] 1235번 - 학생 번호  (0) 2022.03.22
Comments