토마토

Huisu·2023년 8월 9일
0

Coding Test Practice

목록 보기
24/98
post-thumbnail

문제

7569번: 토마토

문제 설명

철수의 토마토 농장에서는 토마토를 보관하는 큰 창고를 가지고 있다. 토마토는 아래의 그림과 같이 격자모양 상자의 칸에 하나씩 넣은 다음, 상자들을 수직으로 쌓아 올려서 창고에 보관한다.
https://upload.acmicpc.net/c3f3343d-c291-40a9-9fe3-59f792a8cae9/-/preview/

창고에 보관되는 토마토들 중에는 잘 익은 것도 있지만, 아직 익지 않은 토마토들도 있을 수 있다. 보관 후 하루가 지나면, 익은 토마토들의 인접한 곳에 있는 익지 않은 토마토들은 익은 토마토의 영향을 받아 익게 된다. 하나의 토마토에 인접한 곳은 위, 아래, 왼쪽, 오른쪽, 앞, 뒤 여섯 방향에 있는 토마토를 의미한다. 대각선 방향에 있는 토마토들에게는 영향을 주지 못하며, 토마토가 혼자 저절로 익는 경우는 없다고 가정한다. 철수는 창고에 보관된 토마토들이 며칠이 지나면 다 익게 되는지 그 최소 일수를 알고 싶어 한다.

토마토를 창고에 보관하는 격자모양의 상자들의 크기와 익은 토마토들과 익지 않은 토마토들의 정보가 주어졌을 때, 며칠이 지나면 토마토들이 모두 익는지, 그 최소 일수를 구하는 프로그램을 작성하라. 단, 상자의 일부 칸에는 토마토가 들어있지 않을 수도 있다.

제한 사항

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100, 1 ≤ H ≤ 100 이다. 둘째 줄부터는 가장 밑의 상자부터 가장 위의 상자까지에 저장된 토마토들의 정보가 주어진다. 즉, 둘째 줄부터 N개의 줄에는 하나의 상자에 담긴 토마토의 정보가 주어진다. 각 줄에는 상자 가로줄에 들어있는 토마토들의 상태가 M개의 정수로 주어진다. 정수 1은 익은 토마토, 정수 0 은 익지 않은 토마토, 정수 -1은 토마토가 들어있지 않은 칸을 나타낸다. 이러한 N개의 줄이 H번 반복하여 주어진다.

토마토가 하나 이상 있는 경우만 입력으로 주어진다.

입출력 예

입력출력
5 3 1
0 -1 0 0 0
-1 -1 0 1 1
0 0 0 1 1-1
5 3 2
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 04
4 3 2
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
-1 -1 -1 -1
1 1 1 -10

아이디어

3차원 배열로 받아서 dx, dy, dz 두고 BFS 진행

한 턴이 끝날 때마다 검사해야 하는 토마토가 que.size()니까 이만큼 poll을 하고 나면 time++

모두 방문했다면 종료해야지만 타임이 더 나가지 않는다

처음에 입력받을 때 애초에 토마토가 있지 않은 칸은 그냥 방문했다고 처리해야 편함

제출 코드


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

// https://www.acmicpc.net/problem/7569
public class five7569 {
    private int[][][] box;
    private int[] dRow = {0, 0, 1, -1, 0, 0};
    private int[] dCol = {1, -1, 0, 0, 0, 0};
    private int[] dHeight = {0, 0, 0, 0, 1, -1};
    private int nCol;
    private int nRow;
    private int nHeight;
    public void solution() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer infoToken = new StringTokenizer(reader.readLine());
        nCol = Integer.parseInt(infoToken.nextToken());
        nRow = Integer.parseInt(infoToken.nextToken());
        nHeight = Integer.parseInt(infoToken.nextToken());

        box = new int[nCol][nRow][nHeight];

        for (int i = 0; i < nHeight; i++) {
            for (int j = 0; j < nRow; j++) {
                StringTokenizer boxToken = new StringTokenizer(reader.readLine());
                for (int k = 0; k < nCol; k++) {
                    box[k][j][i] = Integer.parseInt(boxToken.nextToken());
                }
            }
        }

        boolean[][][] visited = new boolean[nCol][nRow][nHeight];
        Queue<int[]> toVisit = new LinkedList<>();
        boolean complete = true;

        for (int i = 0; i < nHeight; i++) {
            for (int j = 0; j < nRow; j++) {
                for (int k = 0; k < nCol; k++) {
                    if (box[k][j][i] == 1 && !visited[k][j][i]) {
                        toVisit.offer(new int[] {k, j, i});
                    }
                    if(box[k][j][i] == 0) complete = false;
                    else visited[k][j][i] = true;
                }
            }
        }

        int time = 0;
        while(!toVisit.isEmpty()) {
            if (!moreToSearch(visited)) break;
            time++;
            int queSize = toVisit.size();
            for (int num = 0; num < queSize; num++) {
                int[] next = toVisit.poll();
                int currentCol = next[0];
                int currentRow = next[1];
                int currentHeight = next[2];

                if (box[currentCol][currentRow][currentHeight] == -1) continue;

                visited[currentCol][currentRow][currentHeight] = true;

                for (int i = 0; i < 6; i++) {
                    int nextCol = currentCol + dCol[i];
                    int nextRow = currentRow + dRow[i];
                    int nextHeight = currentHeight + dHeight[i];

                    if (
                            checkBounds(nextCol, nextRow, nextHeight) &&
                                    box[nextCol][nextRow][nextHeight] == 0 &&
                                    !visited[nextCol][nextRow][nextHeight]
                    ) {
                        toVisit.offer(new int[]{nextCol, nextRow, nextHeight});
                        visited[nextCol][nextRow][nextHeight] = true;
                        box[nextCol][nextRow][nextHeight] = 1;
                    }
                }
            }
        }

        for (int i = 0; i < nHeight; i++) {
            for (int j = 0; j < nRow; j++) {
                for (int k = 0; k < nCol; k++) {
                    if (box[k][j][i] == 0) {
                        time = -1;
                    }
                }
            }
        }

        if(complete) time = 0;

        System.out.println(time);
    }

    private boolean moreToSearch(boolean[][][] visited) {
        for (int i = 0; i < nHeight; i++) {
            for (int j = 0; j < nRow; j++) {
                for (int k = 0; k < nCol; k++) {
                    if (visited[k][j][i] == false) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean checkBounds(int col, int row, int height) {
        return (-1 < col && col < nCol
                && -1 < row && row < nRow
                && -1 < height && height < nHeight);
    }

    public static void main(String[] args) throws IOException {
        new five7569().solution();
    }
}

1개의 댓글

comment-user-thumbnail
2023년 8월 9일

개발자로서 성장하는 데 큰 도움이 된 글이었습니다. 감사합니다.

답글 달기