유기농 배추 (1012번)
https://www.acmicpc.net/problem/1012
풀이방법
- 전형적인
BFS
문제로, 배추가 있으면서 방문하지 않은 곳인지 확인한다. - 해당 위치부터 상,하,좌,우 위치에 있는 값을 확인해 방문했다는 표시를 남긴다.
- 이렇게 되면 이미 방문한 곳은 제외하므로
BFS
가 끝나면 벌레의 개수를 1증가시킨다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static boolean[][] visited;
static Queue<int[]> queue = new LinkedList<>();
static int[][] map;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = null;
int T = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
int bugCount = 0;
while (T-- > 0) {
st = new StringTokenizer(br.readLine());
int M = Integer.parseInt(st.nextToken());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
map = new int[N][M];
visited = new boolean[N][M];
for(int i=0; i<K; i++) {
st = new StringTokenizer(br.readLine());
int X = Integer.parseInt(st.nextToken());
int Y = Integer.parseInt(st.nextToken());
map[Y][X] = 1;
}
for(int i=0; i<N; i++) {
for (int j=0; j<M; j++) {
if (map[i][j] == 1 && !visited[i][j]) {
bfs(j, i, M, N);
bugCount++;
}
}
}
sb.append(bugCount).append('\n');
bugCount = 0;
}
System.out.println(sb);
}
public static void bfs(int x, int y, int m, int n) {
queue.add(new int[] { x, y });
visited[y][x] = true;
int[] cur;
int[] xPos = {1, 0, -1, 0};
int[] yPos = {0, 1, 0, -1};
int dx = 0; int dy = 0;
while (!queue.isEmpty()) {
cur = queue.poll();
for (int i=0; i<4; i++) {
dx = cur[0] + xPos[i];
dy = cur[1] + yPos[i];
if (dx < 0 || dx >= m || dy < 0 || dy >= n) continue;
if (visited[dy][dx] || map[dy][dx] != 1) continue;
visited[dy][dx] = true;
queue.add(new int[] { dx, dy });
}
}
}
}
Comments powered by Disqus.