Coding Test - cpp/BFS
[백준 1012 : 유기농 배추] - C++
에드윈H
2021. 1. 12. 15:28
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <string.h> //memset 용
using namespace std;
struct Location
{
int x;
int y;
Location(int _x, int _y)
{
x = _x;
y = _y;
}
};
int main()
{
int map[50][50];
memset(map, 0, sizeof(map)); //초기화
int M, N, K;
int dx[4] = { -1,0,1,0 }; //4방향용
int dy[4] = { 0,1,0,-1 }; //4방향용
int test= 0;
cin >> test;
for (int e=0; e < test; e++) {
cin >> M >> N >> K;
int a, b;
for (int i = 0; i < K; i++)
{
cin >> a >> b;
map[a][b] = 1;
}
queue<Location> Q;
int Cnt = 0;
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
if (map[i][j] == 1)
{
map[i][j] = 0;
Q.push(Location(i, j));
while (!Q.empty())
{
Location tmp = Q.front();
Q.pop();
for (int k = 0; k < 4; k++)
{
int xx = dx[k] + tmp.x;
int yy = dy[k] + tmp.y;
if (xx < 0 || M <= xx || yy < 0 || N <= yy)
continue;
if (map[xx][yy] == 1)
{
map[xx][yy] = 0;
Q.push(Location(xx, yy));
}
}
}
Cnt++;
}
}
}
cout << Cnt << endl;
}
return 0;
}