백준(Java)/23년 8월

[Java] 백준 - 7569번: 토마토 - 2

C0MPAS 2023. 8. 11. 14:38

8월 11일(금) - 그래프와 순회 (7569번)

 

7569번: 토마토

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

www.acmicpc.net

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

 

문제점

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

 

풀이

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 {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        StringTokenizer st = new StringTokenizer(br.readLine(), " ");

        int[] dx = {-1, 1, 0, 0, 0, 0};
        int[] dy = {0, 0, -1, 1, 0, 0};
        int[] dz = {0, 0, 0, 0, -1, 1};
        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];
        int cnt = 0;
        int days = 0;
        Queue<int[]> que = new LinkedList<>();

        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++) {
                    int num = Integer.parseInt(st.nextToken());
                    tomato[h][n][m] = num;
                    if (tomato[h][n][m] == 1) {
                        que.add(new int[]{h, n, m});
                    } else if (tomato[h][n][m] == 0) {
                        cnt++;
                    }
                }
            }
        }

        while(cnt > 0 && !que.isEmpty())
        {
            for(int s = que.size(); s>0; s--)
            {
                int[] cur = que.poll();

                for(int k=0; k<6; k++)
                {
                    int next_z = cur[0] + dz[k];
                    int next_y = cur[1] + dy[k];
                    int next_x = cur[2] + dx[k];

                    if(next_x<0 || next_y<0 || next_z<0 || next_x>=M || next_y>=N || next_z>=H || tomato[next_z][next_y][next_x] != 0)
                    {
                        continue;
                    }
                    cnt--;
                    tomato[next_z][next_y][next_x] = 1;
                    que.add(new int[] {next_z, next_y, next_x});
                }
            }
            days++;
        }
        System.out.println(cnt == 0 ? days : -1);
    }
}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ