문제
상근이는 자신의 결혼식에 학교 동기 중 자신의 친구와 친구의 친구를 초대하기로 했다. 상근이의 동기는 모두 N명이고, 이 학생들의 학번은 모두 1부터 N까지이다. 상근이의 학번은 1이다.
상근이는 동기들의 친구 관계를 모두 조사한 리스트를 가지고 있다. 이 리스트를 바탕으로 결혼식에 초대할 사람의 수를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 상근이의 동기의 수 n (2 ≤ n ≤ 500)이 주어진다. 둘째 줄에는 리스트의 길이 m (1 ≤ m ≤ 10000)이 주어진다. 다음 줄부터 m개 줄에는 친구 관계 ai bi가 주어진다. (1 ≤ ai < bi ≤ n) ai와 bi가 친구라는 뜻이며, bi와 ai도 친구관계이다.
출력
첫째 줄에 상근이의 결혼식에 초대하는 동기의 수를 출력한다.
**DFS**
int n, m;
vector<int> graph[501];
bool visited[501];
int cnt;
void DFS(int idx, int depth)
{
visited[idx] = true;
if (depth == 2)
return;
for (int i = 0; i < graph[idx].size(); i++)
{
int next = graph[idx][i];
DFS(next, depth + 1);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
graph[b].push_back(a);
graph[a].push_back(b);
}
DFS(1, 0);
for (int i = 2; i <= n; i++)
{
if (visited[i])
cnt++;
}
cout << cnt;
}
**BFS**
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n, m;
vector<int> graph[501];
bool visited[501];
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
queue<pair<int,int>> q;
q.push({1, 0});
visited[1] = true;
int cnt = 0;
while (!q.empty()) {
auto [cur, depth] = q.front();
q.pop();
if (depth == 2) continue; // 친구의 친구까지만
for (int next : graph[cur]) {
if (!visited[next]) {
visited[nex t] = true;
cnt++;
q.push({next, depth + 1});
}
}
}
cout << cnt;
return 0;
}