백준 - 1012번(유기농 배추)

최지홍·2022년 3월 30일
0

백준

목록 보기
110/145

문제 출처: https://www.acmicpc.net/problem/1012


문제

  • 차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 효과적인 배추흰지렁이를 구입하기로 결심한다. 이 지렁이는 배추근처에 서식하며 해충을 잡아 먹음으로써 배추를 보호한다. 특히, 어떤 배추에 배추흰지렁이가 한 마리라도 살고 있으면 이 지렁이는 인접한 다른 배추로 이동할 수 있어, 그 배추들 역시 해충으로부터 보호받을 수 있다. 한 배추의 상하좌우 네 방향에 다른 배추가 위치한 경우에 서로 인접해있는 것이다.

  • 한나가 배추를 재배하는 땅은 고르지 못해서 배추를 군데군데 심어 놓았다. 배추들이 모여있는 곳에는 배추흰지렁이가 한 마리만 있으면 되므로 서로 인접해있는 배추들이 몇 군데에 퍼져있는지 조사하면 총 몇 마리의 지렁이가 필요한지 알 수 있다. 예를 들어 배추밭이 아래와 같이 구성되어 있으면 최소 5마리의 배추흰지렁이가 필요하다. 0은 배추가 심어져 있지 않은 땅이고, 1은 배추가 심어져 있는 땅을 나타낸다.


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

public class Main {

    public static void main(String[] args) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        int T = Integer.parseInt(reader.readLine());

        for (int t = 0; t < T; t++) {
            StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
            int M = Integer.parseInt(tokenizer.nextToken()); // 가로길이(열)
            int N = Integer.parseInt(tokenizer.nextToken()); // 세로길이(행)
            int K = Integer.parseInt(tokenizer.nextToken()); // 배추 개수

            int[][] matrix = new int[N][M];

            for (int i = 0; i < K; i++) {
                tokenizer = new StringTokenizer(reader.readLine());
                int x = Integer.parseInt(tokenizer.nextToken());
                int y = Integer.parseInt(tokenizer.nextToken());
                matrix[y][x] = 1;
            }

            int cnt = 0;

            for (int i = 0; i < N; i++) {
                for (int j = 0; j < M; j++) {
                    if (matrix[i][j] == 1) {
                        cnt++;
                        bfs(matrix, N, M, i, j);
                    }
                }
            }

            sb.append(cnt).append("\n");
        }

        System.out.println(sb);
    }

    private static void bfs(int[][] matrix, int R, int C, int row, int col) {
        Queue<int[]> queue = new ArrayDeque<>();
        queue.offer(new int[] { row, col });

        int[][] directions = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 }, };
        boolean[][] visited = new boolean[R][C];

        while (!queue.isEmpty()) {
            int[] curr = queue.poll();

            if (visited[curr[0]][curr[1]]) continue;

            visited[curr[0]][curr[1]] = true;
            matrix[curr[0]][curr[1]] = 0;

            for (int i = 0; i < 4; i++) {
                int dy = curr[0] + directions[i][0];
                int dx = curr[1] + directions[i][1];

                if (dy >= 0 && dy < R && dx >= 0 && dx < C) {
                    if (matrix[dy][dx] == 1 && !visited[dy][dx]) queue.offer(new int[] { dy, dx });
                }
            }
        }
    }

}

  • BFS를 연습하기 위해 고른 문제이다. DFS를 사용해도 무방하나 복습을 위해 BFS를 사용하였다.
profile
백엔드 개발자가 되자!

0개의 댓글