-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1260.py
45 lines (35 loc) · 1.01 KB
/
1260.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
# DFS와 BFS
import sys
from collections import defaultdict, deque
N, M, V = map(int, sys.stdin.readline().split(" "))
graph = defaultdict(list)
for _ in range(M):
a, b = map(int, sys.stdin.readline().split(" "))
graph[a].append(b)
graph[b].append(a)
def DFS(graph, root):
visited = []
stack = [root]
while stack:
n = stack.pop()
if n not in visited:
visited.append(n)
if n in graph:
temp = list(set(graph[n]) - set(visited))
temp.sort(reverse=True)
stack += temp
return " ".join(str(i) for i in visited)
def BFS(graph, root):
visited = []
queue = deque([root])
while queue:
n = queue.popleft()
if n not in visited:
visited.append(n)
if n in graph:
temp = list(set(graph[n]) - set(visited))
temp.sort()
queue += temp
return " ".join(str(i) for i in visited)
print(DFS(graph, V))
print(BFS(graph, V))