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
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
 
using namespace std;
int m, n, k;
int cnt;
vector<vector<int>> map(51vector<int>(510));
vector<vector<bool>> visit(51vector<bool>(51false));
 
void dfs(int row, int col) {
    visit[row][col] = true;
 
    if (row - 1 >= 1 && !visit[row - 1][col] && map[row - 1][col] == 1)
        dfs(row - 1, col); //위
 
    if (row + 1 <= n && !visit[row + 1][col] && map[row + 1][col] == 1)
        dfs(row + 1, col); //아래
 
    if (col - 1 >= 1 && !visit[row][col - 1&& map[row][col - 1== 1)
        dfs(row, col - 1); //왼쪽
 
    if (col + 1 <= m && !visit[row][col + 1&& map[row][col + 1== 1)
        dfs(row, col + 1); //오른쪽
}
 
int main() {
    int t;
    scanf("%d"&t);
 
    for (int tc = 0; tc < t; tc++) {
        //각 테스트케이스마다 초기화
        cnt = 0;
        map = vector<vector<int>>(51vector<int>(510));
        visit = vector<vector<bool>>(51vector<bool>(51false));
 
        scanf("%d %d %d"&m, &n, &k);
 
        for (int i = 0; i < k; i++) {
            int a, b;
            scanf("%d %d"&a, &b);
 
            map[b + 1][a + 1= 1;
        }
 
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (map[i][j] == 1 && !visit[i][j]) {
                    dfs(i, j);
                    ++cnt;
                }
            }
        }
 
        printf("%d\n", cnt);
    }
 
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

단지번호붙이기랑 똑같은 문제

 

'Baekjoon' 카테고리의 다른 글

[#7576] 토마토  (0) 2020.03.31
[#2178] 미로탐색  (0) 2020.03.31
[#2667] 단지번호붙이기  (0) 2020.03.31
[#1260] DFS와 BFS  (0) 2020.03.31
[#11286] 절댓값 힙  (0) 2020.03.17

+ Recent posts