[백준 24446] - 알고리즘 수업 - 너비 우선 탐색 3 (실버2)
https://www.acmicpc.net/problem/24446

bfs(너비우선탐색) 문제로 우선 bfs 함수 구현하면 된다.
문제 조건에 따라 노드의 깊이는 -1로 초기화한다.
bfs 탐색 시 노드 깊이를 업데이트 한다.
먼저 최초 방문 시 노드 깊이 = 0 으로 설정하고,
이후 queue 에서 탐색 하면서 다음 노드 깊이 = 현재 노드 깊이 +1 로 만든다.
이후 정점번호는 1부터임을 주의하며 1~ n 번 까지 정점의 깊이를 출력하면 된다.
예제 넣고 테스트 한 뒤 통과 확인

전체 코드
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
#include <climits>
#include <queue>
#include <cstring>
using namespace std;
vector<int> vec[200001];
bool visited[200001];
int depth[200001];
void bfs(int n)
{
queue<int> q;
visited[n] = true;
depth[n] = 0;
q.push(n);
for (int i = 0; i < vec[n].size(); i++)
{
q.push(vec[n][i]);
}
while (!q.empty())
{
int curr = q.front();
q.pop();
for (int i = 0; i < vec[curr].size(); i++)
{
int next = vec[curr][i];
if (!visited[next])
{
q.push(next);
visited[next] = true;
depth[next] = depth[curr] + 1;
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, r;
cin >> n >> m >> r;
// 노드 깊이 초기화
for (int i = 1; i <= n; i++)
{
depth[i] = -1;
}
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
vec[u].push_back(v);
vec[v].push_back(u);
}
bfs(r);
for (int i = 1; i <= n; i++)
{
cout << depth[i] << "\n";
}
return 0;
}'백준 > 실버' 카테고리의 다른 글
| [백준 1158] - 요세푸스 문제(C++) (1) | 2025.12.16 |
|---|---|
| [백준 4659] - 비밀번호 발음하기(C++) (1) | 2025.08.19 |
| 백준 [13022] - 늑대와 올바른 단어 (c++) (0) | 2025.03.17 |
| 백준 [2108] - 통계학 (c++) (0) | 2025.02.04 |
| 백준[4134] - 다음 소수 (c++) (0) | 2025.01.24 |