Taene's
[백준] 실버2-유기농 배추 C++ 1012번 본문
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;
}'백준 > 실버' 카테고리의 다른 글
| [백준] 실버1-쿼드트리 C++ 1992번 (0) | 2025.02.23 |
|---|---|
| [백준] 실버1-영역 구하기 C++ 2583번 (0) | 2025.02.23 |
| [백준] 실버1-안전 영역 C++ 2468번 (0) | 2025.02.22 |
| [백준] 실버1-미로 탐색 C++ 2178번 (0) | 2025.02.22 |
| [백준] 실버3-한국이 그리울 땐 서버에 접속하지 C++ 9996번 (0) | 2025.02.22 |