https://www.acmicpc.net/problem/1012
DFS
#include <iostream>
using namespace std;
int M;
int N;
void dfs(int x, int y, int input[][52], int check[][52])
{
check[x][y] = 1;
int dx[] = { 0, 0, 1, -1 };
int dy[] = { 1, -1, 0, 0 };
for (int i = 0; i < 4; i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && ny >= 0 && nx < M && ny < N) {
if (!check[nx][ny] && input[nx][ny] == 1) {
dfs(nx, ny, input, check);
}
}
}
}
int main()
{
int T;
cin >> T;
for (int i = 0; i < T; i++)
{
int K;
cin >> M >> N >> K;
int input[52][52] = { 0, };
int check[52][52] = { 0, };
//plant cabbage
for (int j = 0; j < K; j++)
{
int x;
int y;
cin >> x >> y;
input[x][y] = 1;
}
int count = 0;
for (int l = 0; l < M; l++)
{
for (int p = 0; p < N; p++)
{
if (!check[l][p] && input[l][p]) {
dfs(l, p, input, check);
count++;
}
}
}
cout << count << endl;
}
}
'알고리즘 문제 풀이' 카테고리의 다른 글
[백준] - 수열 정렬 - 복습 (0) | 2021.01.31 |
---|---|
[백준] - Contact - 복습 (0) | 2021.01.31 |
[백준] - Fly me to the Alpha Centauri - 복습 (0) | 2021.01.31 |
[백준] - 다리 놓기 - 복습 (0) | 2021.01.31 |
[백준] - 분산처리 - 복습 (0) | 2021.01.30 |
댓글