본문 바로가기
알고리즘/백준

[백준] 온라인 저지 1012번 : 유기농 배추(Java), BFS

by hxxyeoniii 2025. 2. 5.

BFS로 풀이하면 간단한 문제

 

import java.util.*;

public class P1012_유기농배추 {
    static int[] dx = {0, 1, 0, -1};
    static int[] dy = {1, 0, -1, 0};
    static boolean[][] visited;
    static int[][] arr;
    static int M, N;

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

        for(int i=0; i<testCase; i++) {
            M = sc.nextInt(); // 가로
            N = sc.nextInt(); // 세로
            int K = sc.nextInt(); // 배추 위치
            int answer = 0;

            arr = new int[N][M]; // 배추밭
            visited = new boolean[N][M]; // 방문배열

            for(int j=0; j<K; j++) {
                int x = sc.nextInt();
                int y = sc.nextInt();

                arr[y][x] = 1; // 1 : 지렁이
            }

            for(int l=0; l<N; l++) {
                for(int k=0; k<M; k++) {
                    if(arr[l][k] == 1 && !visited[l][k]) {
                        answer++;
                        BFS(l, k);
                    }
                }
            }
            System.out.println(answer);
        }

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

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

            for(int k=0; k<4; k++) {
                int x = now[0] + dx[k];
                int y = now[1] + dy[k];

                if(x>=0 && y>=0 && x<N && y<M) {
                    if(arr[x][y] == 1 && !visited[x][y]) {
                        q.offer(new int[] {x, y});
                        visited[x][y] = true;
                    }
                }
            }
        }

    }
}

 

아직도 BFS나 DFS 문제 풀이 시 배열 범위가 헷갈리는 것 같다..