BFS를 이용해 몇개의 덩어리가 있는지 판단하는 문제이다.
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int N, M, K;
vector <vector<int>> map(50, vector<int>(50, 0));
vector <vector<bool>> visited(50, vector<bool>(50, false));
void reinit_map_and_visited()
{
int i, j;
for (i = 0; i < 50; i++)
{
for (j = 0; j < 50; j++)
{
//i = y축, j는 x축
map[i][j] = 0;
visited[i][j] = false;
}
}
return;
}
void input_map()
{
int i, X, Y;
for (i = 0; i < K; i++)
{
cin >> X >> Y;//a = x, b = y
map[X][Y] = 1;
}
return;
}
void BFS(int start_x, int start_y)
{
int current_x, current_y, next_x, next_y;
queue <pair<int, int>> q;
vector<vector<int>> direction = { {1, 0}, {0, -1}, {-1, 0}, {0, 1}};
int i;
visited[start_y][start_x] = true;
q.push({ start_x, start_y });
while (q.empty() == false)
{
current_x = q.front().first;
current_y = q.front().second;
q.pop();
for (i = 0; i < direction.size(); i++)
{
next_x = current_x + direction[i][0];
next_y = current_y + direction[i][1];
if ((next_x >= 0 && next_x < M) && (next_y >= 0 && next_y < N) && (map[next_y][next_x] == 1) && visited[next_y][next_x] == false)
{
visited[next_y][next_x] = true;
q.push({ next_x, next_y });
}
else
{
;
}
}
}
return;
}
int find_result()
{
int i, j, count = 0;
for (i = 0; i < N; i++)
{
for (j = 0; j < M; j++)
{
if (visited[i][j] == false && map[i][j] == 1)
{
BFS(j, i);
count++;
}
}
}
return count;
}
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int T;
cin >> T;
while (T > 0)
{
cin >> N >> M >> K;
input_map();
cout << find_result() << "\n";
reinit_map_and_visited();
T--;
}
return 0;
}