728x90
https://www.acmicpc.net/problem/24479
문제 분석
입력 받아 그래프를 만들고 DFS로 탐색을 하고, 탐색 순서를 기록하여 출력하는 형식에 문제이다.
이 문제는 DFS만 알고 있다면 딱히 문제 없이 풀 수 있을 것이라고 생각된다.
코드
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> graph;
vector<bool> visited;
int result[100001];
int cnt = 0;
void DFS(int index);
int main()
{
int n, m, r, input1, input2;
cin >> n >> m >> r;
graph.resize(n + 1);
visited.resize(n + 1, false);
while (m--)
{
cin >> input1 >> input2;
graph[input1].push_back(input2);
graph[input2].push_back(input1);
}
for (int i = 1; i < graph.size(); ++i)
sort(graph[i].begin(), graph[i].end());
DFS(r);
for (int i = 1; i <= n; i++)
cout << result[i] << '\n';
}
void DFS(int index)
{
if (visited[index])
return;
visited[index] = true;
++cnt;
result[index] = cnt;
for (int i : graph[index])
DFS(i);
}
728x90
'ALGORITHM > C++ - 백준' 카테고리의 다른 글
[백준 14940] 쉬운 최단거리 (0) | 2023.10.18 |
---|---|
[백준 16928] 뱀과 사다리 게임 (1) | 2023.10.18 |
[백준 10026] 적록색약 (1) | 2023.10.18 |
[백준 1260] DFS와 BFS (0) | 2023.08.01 |
[백준 11724] 연결 요소의 개수 (0) | 2023.08.01 |
댓글