문제
https://www.acmicpc.net/problem/1012
문제 설명
코드
import java.util.*;
import java.io.*;
class Main {
static boolean[][] map;
static boolean[][] visit;
static Queue<int[]> q;
static void BFS() {
while (!q.isEmpty()) {
int[] value = q.poll();
int x = value[0];
int y = value[1];
if (x >= 0 && y >= 0) {
if (!visit[x][y] && map[x][y]) {
q.offer(new int[]{x, y - 1});
q.offer(new int[]{x, y + 1});
q.offer(new int[]{x - 1, y});
q.offer(new int[]{x + 1, y});
}
visit[x][y] = true;
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while (T-- > 0) {
String[] sArr = br.readLine().split(" ");
int M = Integer.parseInt(sArr[0]);
int N = Integer.parseInt(sArr[1]);
int K = Integer.parseInt(sArr[2]);
int count = 0;
map = new boolean[51][51];
visit = new boolean[51][51];
q = new LinkedList<>();
while (K-- > 0) {
String[] arr = br.readLine().split(" ");
map[Integer.parseInt(arr[0])][Integer.parseInt(arr[1])] = true;
}
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (!visit[i][j] && map[i][j]) {
count++;
q.add(new int[]{i, j});
BFS();
}
}
}
System.out.println(count);
}
}
}
'🧑💻코딩 테스트 > 백준 (BOJ)' 카테고리의 다른 글
[코딩테스트/백준 알고리즘] 11724번 - 연결 요소의 개수 (Java, 자바 풀이) (0) | 2022.12.22 |
---|---|
[코딩테스트/백준 알고리즘] 18870번 - 좌표 압축 (Java, 자바 풀이) (0) | 2022.12.21 |
[코딩 테스트/백준 알고리즘] 5430번 - AC (Java, 자바 풀이) (0) | 2022.12.16 |
[코딩테스트/백준 알고리즘] 2606번 - 바이러스 (Java, 자바 풀이) (0) | 2022.12.15 |
[코딩테스트/백준 알고리즘] 1927번 - 최소 힙 (Java, 자바 풀이) (2) | 2022.12.14 |
댓글