-
Notifications
You must be signed in to change notification settings - Fork 0
/
1012.cpp
62 lines (56 loc) · 1.29 KB
/
1012.cpp
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
#include <iostream>
#include <queue>
using namespace std;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
queue<pair<int,int> > q;
int graph[50][50];
int visited[50][50];
int N,M,K;
void BFS(int x,int y){
q.push(pair<int,int>(x,y));
while(!q.empty()){
int vx = q.front().first;
int vy = q.front().second;
q.pop();
visited[vx][vy] = 1;
for(int i=0;i<4;i++){
int xx = vx+dx[i];
int yy = vy+dy[i];
if(xx >= 0 && yy >= 0 && xx < N && yy < M && !visited[xx][yy] && graph[xx][yy] == 1){
visited[xx][yy] = true;
q.push(pair<int,int>(xx,yy));
}
}
}
}
void init() {
while (!q.empty()) q.pop();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
visited[i][j] = false;
graph[i][j] = 0;
}
}
}
int main(){
int T; cin>>T;
for(int t=0; t<T; t++){
init();
int cnt=0;
cin>>M>>N>>K;
for(int i=0; i<K;i++){
int x,y; cin>>y>>x;
graph[x][y]=1;
}
for(int i=0; i<N; i++){
for (int j=0; j< M; j++){
if(graph[i][j]==1 && visited[i][j]==0){
BFS(i,j);
cnt++;
}
}
}
cout << cnt<<endl;
}
}