배추를 지키기 위해 필요한 지렁이의 마리 수를 구하는 문제.
연결된 배추의 영역의 개수를 구하면 된다.
DFS로도 풀 수 있지만 BFS를 이용하여 풀어보았다.
입력으로 주어진 배추의 위치를 2차원 배열에 저장하여, 예시로 주어진 것과 같은 표를 만든다.
표의 (0,0)부터 (n-1,n-1)까지 탐색하면서 1을 만나면 BFS 함수를 실행, 탐색이 완료된 칸은 visited 배열을 업데이트 한다.
모든 좌표의 탐색을 완료하면 영역의 개수를 출력한다.
#include <iostream>
#include <queue>
using namespace std;
int t, m, n, k;
int arr[50][50];
bool visited[50][50];
int cnt = 0;
queue<pair<int, int>> q;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, -1, 0, 1};
void init()
{
for (int i = 0; i < 50; i++)
{
for (int j = 0; j < 50; j++)
{
arr[i][j] = 0;
visited[i][j] = false;
}
}
}
void bfs(int xx, int yy)
{
q.push({xx, yy});
while (!q.empty())
{
int x = q.front().first;
int y = q.front().second;
q.pop();
visited[x][y] = true;
for (int i = 0; i < 4; i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && ny >= 0 && nx < n && ny < m && !visited[nx][ny] && arr[nx][ny] == 1)
{
visited[nx][ny] = true;
q.push({nx, ny});
}
}
}
}
int main()
{
cin >> t;
while (t > 0)
{
init();
cin >> m >> n >> k;
int a, b;
for (int i = 0; i < k; i++)
{
cin >> a >> b;
arr[b][a] = 1;
}
for (int x = 0; x < n; x++)
{
for (int y = 0; y < m; y++)
{
if (arr[x][y] == 1 && !visited[x][y])
{
bfs(x, y);
cnt++;
}
}
}
t--;
cout << cnt << endl;
cnt = 0;
}
return 0;
}