PS/Problems

[Java] (시간 17등) 백준 7576번

CalicoCat22 2021. 12. 27. 23:31
import java.util.*;
import java.io.*;

public class s1_7576 {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Queue<int[]> q = new LinkedList<>();
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());
        // q : 익은 사과칸 (이미 조회한 것은 제외시킴)

        int goal = 0;
        int[][] check = new int[M][N];
        for (int i = 0; i < M; i++){
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < N; j++){
                int temp = Integer.parseInt(st.nextToken());
                check[i][j] = temp;
                
                if (temp == 0){
                    goal++;
                }
                else if (temp == 1){
                    q.add(new int[]{i, j});
                }
            }
        }

        int day = 0;
        int cnt = goal;
        
        while (goal != 0){
            day++;
            goal = find(q, check, goal);
            if (cnt == goal){
                System.out.println(-1);
                return;
            }
            cnt = goal;
        }
        // goal : 익어야 하는 사과의 개수 (0 도달 : 전부 익었다는 뜻)
        System.out.println(day);
    }

    public static int find(Queue<int[]> q, int[][] check, int goal){
        // q에 저장된 위치 인근의 사과를 익게 함
        int size = q.size();

        for (int i = 0; i < size; i++){
            int[] temp = q.poll();
            int row = temp[0];
            int col = temp[1];

            if (row > 0 && check[row - 1][col] == 0){
                check[row - 1][col] = 1;
                goal--;
                q.add(new int[]{row - 1, col});
            }
            if (row < check.length - 1 && check[row + 1][col] == 0){
                check[row + 1][col] = 1;
                goal--;
                q.add(new int[]{row + 1, col});
            }
            if (col > 0 && check[row][col - 1] == 0){
                check[row][col - 1] = 1;
                goal--;
                q.add(new int[]{row, col - 1});
            }
            if (col < check[0].length - 1 && check[row][col + 1] == 0){
                check[row][col + 1] = 1;
                goal--;
                q.add(new int[]{row, col + 1});
            }
        }

        return goal;
    }
}