본문 바로가기
Algorithm Study/BaekJoon (JAVA)

백준 1012_유기농 배추_JAVA

by 창브로 2024. 4. 2.
728x90

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

 

1012번: 유기농 배추

차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 

www.acmicpc.net

 

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

public class Main {
    static int T, M, N, K;
    static int[][] grid;
    static boolean[][] visited;
    static int count;
    static int[] dx = {1, -1, 0, 0};
    static int[] dy = {0, 0, 1, -1};

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        T = Integer.parseInt(br.readLine()); // 테스트 케이스 갯수

        for (int a = 0; a < T; a++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            M = Integer.parseInt(st.nextToken()); // 가로 길이
            N = Integer.parseInt(st.nextToken()); // 세로 길이
            K = Integer.parseInt(st.nextToken()); // 배추 갯수
            grid = new int[N][M];
            visited = new boolean[N][M];
            count = 0;

            for (int i = 0; i < K; i++) {
                st = new StringTokenizer(br.readLine());
                int y = Integer.parseInt(st.nextToken());
                int x = Integer.parseInt(st.nextToken());

                grid[x][y] = 1;
            }

            for (int j = 0; j < N; j++) {
                for (int l = 0; l < M; l++) {
                    if (!visited[j][l] && grid[j][l] == 1) {
                        visited[j][l] = true;
                        dfs(j, l);
                        count++;
                    }
                }
            }
            System.out.println(count);
        }
    }

    private static void dfs(int x, int y) {

        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 && !visited[nx][ny] && grid[x][y] == 1) {
                visited[nx][ny] = true;
                dfs(nx, ny);
            }
        }
    }
}

회고

- 간단한 DFS 문제였다.

- 스스로 풀어내서 기분이 좋다.

 

 

'Algorithm Study > BaekJoon (JAVA)' 카테고리의 다른 글

백준 2667_단지번호붙이기_JAVA  (1) 2024.04.03
백준 2468_안전영역_JAVA  (0) 2024.04.03
백준 2193_이친수_JAVA  (1) 2024.04.01
백준 1463_1로 만들기_JAVA  (0) 2024.04.01
백준 9655_돌 게임_JAVA  (0) 2024.04.01