백준 7569번 토마토 JAVA

YB·2024년 12월 29일

링크텍스트

설명

3차원 배열은 컴퓨터에서 배열 안에 배열을 저장하는 방식으로 구현된다. 이때 배열의 순서는 (z, y, x) 순으로 구성하는 것이 일반적이다. arr[i][j][k]가 1일 경우 큐에 (z, y, x) 좌표를 추가하고, 0일 경우 zero 카운트를 증가시켰다. bfs()에서는 방문한 좌표를 arr[zz][yy][xx] = 1로 초기화하고, zero를 감소시켜 익지 않은 토마토의 갯수를 줄여나갔다. 큐의 크기만큼 for문을 돌고 나면 days를 증가시켰다

코드

import java.util.*;
import java.io.*;

public class Main {
        static int n,m,h;
        static int [] dx = {1,-1,0,0,0,0};
        static int [] dy = {0,0,-1,1,0,0};
        static int [] dz = {0,0,0,0,1,-1};
        static int [][][] arr;
        static Queue<int []> q = new LinkedList<>();
        static int days = 0;
        static int zero = 0;
    public static void main(String[] args) 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());
        
        arr = new int[h][n][m];
        
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < n; j++) {
                st = new StringTokenizer(br.readLine());
                for (int k = 0; k < m; k++) {
                    arr[i][j][k] = Integer.parseInt(st.nextToken());
                    if(arr[i][j][k]==1){
                        q.add(new int[]{i,j,k});
                    }else if(arr[i][j][k]==0){
                        zero++;
                    }
                }
            }
        }
        bfs();
        System.out.println(zero==0 ? days : -1);
    } 
    public static void bfs(){

        while(!q.isEmpty() && zero>0){
            int size = q.size();

            for(int i=0;i<size;i++){
                int [] current = q.poll();

                int x = current[2];
                int y = current[1];
                int z = current[0];

                for(int j=0;j<6;j++){
                    int xx = x + dx[j];
                    int yy = y + dy[j];
                    int zz = z + dz[j];

                    if(xx>=0&& xx<m && yy>=0 && yy<n && zz>=0 && zz<h && arr[zz][yy][xx]==0){
                        q.add(new int[]{zz,yy,xx});
                        arr[zz][yy][xx]=1;
                        zero--;
                    }
                }
            }
            days++; 
        }
    }
}

profile
안녕하세요

0개의 댓글