Taene's

[백준] 실버2-유기농 배추 C++ 1012번 본문

백준/실버

[백준] 실버2-유기농 배추 C++ 1012번

taene_ 2025. 2. 22. 15:57

https://www.acmicpc.net/problem/1012

 

// 배열을 재사용하기 때문에 초기화 생각하기

#include <iostream>
#include <queue>
#include <map>
using namespace std;

int M, N, K;
int adj[50][50];
bool visited[50][50];
int cnt;
int dy[] = { -1,1,0,0 };
int dx[] = { 0,0,-1,1 };

void clearArr(int y, int x)
{
	cnt = 0;
	for (int i = 0; i < y; i++)
	{
		for (int j = 0; j < x; j++)
		{
			adj[i][j] = 0;
			visited[i][j] = 0;
		}
	}
}

void dfs(int y, int x)
{
	visited[y][x] = 1;

	for (int i = 0; i < 4; i++)
	{
		int ny = y + dy[i];
		int nx = x + dx[i];

		if (ny < 0 || nx < 0 || ny >= N || nx >= M) continue;
		if (visited[ny][nx]) continue;
		if (!adj[ny][nx]) continue;

		dfs(ny, nx);
	}

	return;
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int T;
	cin >> T;
	while (T--)
	{
		cin >> M >> N >> K;
		clearArr(N, M);

		for (int i = 0; i < K; i++)
		{
			int y, x;
			cin >> x >> y;
			adj[y][x] = 1;
		}

		for (int i = 0; i < N; i++)
		{
			for (int j = 0; j < M; j++)
			{
				if (adj[i][j] && !visited[i][j])
				{
					cnt++;
					dfs(i, j);
				}
			}
		}

		cout << cnt << '\n';
	}

	return 0;
}