-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFS와 BFS.py
53 lines (35 loc) · 1020 Bytes
/
DFS와 BFS.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import sys
readline = lambda: sys.stdin.readline().strip()
N, M, V = map(int, readline().split())
GRAPH_SIZE = N + 1
graph = [[] for _ in range(GRAPH_SIZE)]
for _ in range(M):
u, v = map(int, readline().split())
graph[u].append(v)
graph[v].append(u)
for idx in range(len(graph)): # 작은 정점부터 순회
graph[idx] = sorted(graph[idx])
# ================ DFS ================
visited = [False] * GRAPH_SIZE
def dfs(v):
visited[v] = True
print(v, end=" ")
for near in graph[v]:
if not visited[near]:
dfs(near)
dfs(V)
print()
# ================ BFS ================
from collections import deque
def bfs(v):
visited = [False] * GRAPH_SIZE
que = deque([v])
while que:
v = que.popleft()
visited[v] = True
print(v, end=" ")
for near in graph[v]:
if not visited[near]:
que.append(near)
visited[near] = True
bfs(V)