Tech-blog/Algorithm

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

ZeRami 2023. 3. 2. 21:57

 

import java.util.*;

public class OrganicCabbage {
    static int[][] map;
    static boolean[][] visited;
    static int[] dx = {0, 0, 1, -1};
    static int[] dy = {1, -1, 0, 0};
    static int N, M, K;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int T = sc.nextInt(); // 테스트 케이스의 개수

        while (T-- > 0) {
            M = sc.nextInt(); // 가로 길이
            N = sc.nextInt(); // 세로 길이
            K = sc.nextInt(); // 배추가 심어져 있는 위치의 개수

            map = new int[N][M];
            visited = new boolean[N][M];

            for (int i = 0; i < K; i++) {
                int x = sc.nextInt();
                int y = sc.nextInt();
                map[y][x] = 1; // 배추가 심어져 있는 위치 표시
            }

            int count = 0; // 지렁이 개수

            for (int i = 0; i < N; i++) {
                for (int j = 0; j < M; j++) {
                    if (map[i][j] == 1 && !visited[i][j]) { // 배추가 심어져 있고 방문하지 않은 경우
                        dfs(i, j); // dfs 탐색
                        count++;
                    }
                }
            }

            System.out.println(count); // 출력
        }
    }

    public static void dfs(int x, int y) {
        visited[x][y] = true;

        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];

            if (nx < 0 || ny < 0 || nx >= N || ny >= M) continue;
            if (map[nx][ny] == 0 || visited[nx][ny]) continue;

            dfs(nx, ny);
        }
    }
}