https://www.acmicpc.net/problem/24480
24480번: 알고리즘 수업 - 깊이 우선 탐색 2
첫째 줄에 정점의 수 N (5 ≤ N ≤ 100,000), 간선의 수 M (1 ≤ M ≤ 200,000), 시작 정점 R (1 ≤ R ≤ N)이 주어진다. 다음 M개 줄에 간선 정보 u v가 주어지며 정점 u와 정점 v의 가중치 1인 양
www.acmicpc.net
import sys
sys.setrecursionlimit(10**6)
n, m, r = map(int, sys.stdin.readline().split())
graph = [[] for _ in range(n + 1)]
cnt = 1
visited = [False] * (n + 1)
ans = [0] * (n + 1)
for _ in range(m):
a, b = map(int, sys.stdin.readline().split())
graph[a].append(b)
graph[b].append(a)
def dfs(n):
global cnt
visited[n] = True
ans[n] = cnt
cnt += 1
graph[n].sort(reverse=True)
for idx in graph[n]:
if visited[idx] is False:
dfs(idx)
dfs(r)
for i in range(1, n + 1):
print(ans[i])
'자료구조 & 알고리즘 관련 > 코딩테스트' 카테고리의 다른 글
알고리즘 수업 - 너비 우선 탐색 2 (0) | 2023.02.05 |
---|---|
알고리즘 수업 - 너비 우선 탐색 1 (0) | 2023.02.05 |
알고리즘 수업 - 깊이 우선 탐색 1 (0) | 2023.02.05 |
이진 트리 순회 구현 (0) | 2023.02.03 |
Longest Consecutive Sequence (0) | 2023.02.01 |