OJ

[BOJ] 27737 버섯 농장 (JAVA)

P3PP4 2023. 4. 18. 10:00

https://www.acmicpc.net/problem/27737

 

27737번: 버섯 농장

첫 번째 줄에 $N$, $M$, $K$가 공백으로 구분되어 주어진다. 두 번째 줄부터 $N$개의 줄에 나무판의 각 칸의 상태가 공백으로 구분되어 주어진다. 버섯이 자랄 수 있는 칸은 0, 버섯이 자랄 수 없는 칸

www.acmicpc.net

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

public class Main {
	
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer st;
    static int N, M, K, M2;
    static int[][] map;
    static boolean[][] visited;
    static int[] dr = { -1 , 0,  1,  0 };
    static int[] dc = {  0,  1,  0, -1 };

    public static void main(String[] args) throws Exception {

        st = new StringTokenizer(br.readLine(), " ");
        N = Integer.parseInt(st.nextToken());
        M = M2 = Integer.parseInt(st.nextToken());
        K = Integer.parseInt(st.nextToken());
        map = new int[N][N];
        visited = new boolean[N][N];
        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine(), " ");
            for (int j = 0; j < N; j++) {
                map[i][j] = Integer.parseInt(st.nextToken());
            }
        } // end of input

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (map[i][j] == 0 && !visited[i][j]) {
                    bfs(i, j);
                    if (M < 0) {
                        System.out.print("IMPOSSIBLE");
                        return;
                    }
                }
            }
        }

        if (M == M2) System.out.print("IMPOSSIBLE");
        else {
            System.out.println("POSSIBLE");
            System.out.println(M);
        }

    }

    static void bfs(int i, int j) {
        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[] { i, j });
        visited[i][j] = true;
        int cnt = 1;

        while (!q.isEmpty()) {
            int[] a = q.poll();

            for (int dir = 0; dir < 4; dir++) {
                int nr = a[0] + dr[dir];
                int nc = a[1] + dc[dir];

                if (0 <= nr && nr < N && 0 <= nc && nc < N && map[nr][nc] == 0 && !visited[nr][nc]) {
                    q.offer(new int[] { nr, nc });
                    visited[nr][nc] = true;
                    cnt++;
                }
            }
        }

        M -= (cnt + K - 1) / K;
    }
	
}