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 문제 풀이 시 배열 범위가 헷갈리는 것 같다..
'알고리즘 > 백준' 카테고리의 다른 글
| [백준] 온라인 저지 2579번 : 계단 오르기(Java), DP (1) | 2025.08.31 |
|---|---|
| [백준] 온라인 저지 7576번 : 토마토(Java), BFS (3) | 2025.08.27 |
| [백준] 온라인 저지 12845번 : 모두의 마블(Java), 그리디 (3) | 2025.02.04 |
| [백준] 온라인 저지 11399번 : ATM(Java), 그리디 & 삽입 정렬 (0) | 2025.02.03 |
| [백준] 온라인 저지 14586번 : 퇴사 2(Java), DP (1) | 2025.01.23 |