[BOJ] 알고리즘 수업 - 너비 우선 탐색 3 - 24446 (S2)
[BOJ] 알고리즘 수업 - 너비 우선 탐색 3 - 24446 (S2)
| 시간 제한 | 메모리 제한 |
|---|---|
| 1 초 | 512 MB |
문제
BFS를 수행하면서 각 노드의 깊이를 구하는 문제이다.
풀이
BFS 문제이다. 깊이 정보를 함께 저장한다.
코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import sys
from collections import deque
input = sys.stdin.readline
N, M, R = map(int, input().split())
graph = [[] for _ in range(N + 1)]
for _ in range(M):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
def bfs(start):
q = deque([(start, 0)])
visited = [-1] * (N + 1)
visited[start] = 0
while q:
cur_node, d = q.popleft()
for n_node in graph[cur_node]:
if visited[n_node] != -1:
continue
visited[n_node] = d + 1
q.append((n_node, d + 1))
return visited[1:]
print(*bfs(R), sep='\n')
시간 복잡도
O(N + M)
This post is licensed under CC BY 4.0 by the author.