[백준] 1012 유기농 배추
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int N, M;
int board[55][55];
int visited[55][55];
bool inRange(int r, int c) {
if (r < 0 || r >= N) return false;
if (c < 0 || c >= M) return false;
return true;
}
int dirR[4] = { 0, 0, 1, -1 };
int dirC[4] = { 1, -1, 0, 0 };
void bfs(int startR, int startC) {
queue<pair<int, int>> q;
q.push({ startR, startC });
while (!q.empty()) {
int curR = q.front().first;
int curC = q.front().second;
q.pop();
if (visited[curR][curC]) continue;
visited[curR][curC] = 1;
for (int d = 0; d < 4; ++d) {
int nextR = curR + dirR[d];
int nextC = curC + dirC[d];
if (!inRange(nextR, nextC)) continue;
if (visited[nextR][nextC]) continue;
if (board[nextR][nextC] == 0) continue;
q.push({ nextR, nextC });
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int T;
cin >> T;
while (T--) {
for (int i = 0; i <= 50; ++i) {
for (int j = 0; j <= 50; ++j) {
board[i][j] = 0;
visited[i][j] = 0;
}
}
cin >> M >> N;
int K;
cin >> K;
for(int i = 0; i<K; ++i){
int x, y;
cin >> x >> y;
board[y][x] = 1;
}
int cnt = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
if ((board[i][j] == 1) && (!visited[i][j])) {
bfs(i, j);
cnt++;
}
}
}
cout << cnt << "\n";
}
return 0;
}