반응형
https://www.acmicpc.net/problem/1068
1068번: 트리
첫째 줄에 트리의 노드의 개수 N이 주어진다. N은 50보다 작거나 같은 자연수이다. 둘째 줄에는 0번 노드부터 N-1번 노드까지, 각 노드의 부모가 주어진다. 만약 부모가 없다면 (루트) -1이 주어진다. 셋째 줄에는 지울 노드의 번호가 주어진다.
www.acmicpc.net
1. 해결방법
N, M의 최대수가 적으므로 DFS를 통해 해결하였다.
2. 코드
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int test_case;
int M,N,K;
int ary[51][51];
int chk[51][51];
int dx[4] = { 0, 0, -1, 1 };
int dy[4] = { -1, 1, 0, 0 };
int result = 0;
void dfs(int x, int y) {
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx >= M || ny < 0 || ny >= N || chk[nx][ny] || ary[nx][ny] == 0) continue;
else {
chk[nx][ny] = 1;
dfs(nx, ny);
}
}
}
int main()
{
cin >> test_case;
for (int i = 0; i < test_case; i++) {
cin >> M;
cin >> N;
cin >> K;
memset(ary, 0, sizeof(ary));
memset(chk, 0, sizeof(chk));
result = 0;
for (int j = 0; j < K; j++) {
int x, y;
cin >> x >> y;
ary[x][y] = 1;
}
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (ary[i][j] == 1 && chk[i][j] == 0) {
chk[i][j] = 1;
dfs(i, j);
result++;
}
}
}
cout << result << endl;
}
}
반응형
'코딩테스트 > 백준' 카테고리의 다른 글
[백준] #1197 램프 (0) | 2020.05.08 |
---|---|
[백준] #1034 램프 (0) | 2020.04.13 |
[백준] #1068 트리 (0) | 2020.03.29 |