-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1260-DFS와BFS.py
More file actions
51 lines (41 loc) · 1.02 KB
/
1260-DFS와BFS.py
File metadata and controls
51 lines (41 loc) · 1.02 KB
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
import sys
from collections import deque
N, M, V = map(int, sys.stdin.readline().strip().split(' '))
graph = [[] for _ in range(N+1)]
if M == 0:
print(V)
print(V)
sys.exit()
for _ in range(M) :
x, y = map(int, sys.stdin.readline().strip().split(' '))
graph[x].append(y)
graph[y].append(x)
for i in range(N+1) :
graph[i].sort()
if len(graph[V]) == 0 :
print(V)
print(V)
sys.exit()
def DFS(graph, start, visited=[]) :
visited.append(start)
for node in graph[start] :
if node not in visited :
DFS(graph, node, visited)
return visited
def BFS(graph, start, visited=[]) :
queue = deque([start])
visited.append(start)
while queue :
v = queue.popleft()
for i in graph[v] :
if i not in visited:
queue.append(i)
visited.append(i)
return visited
result1 = DFS(graph, V)
result2 = BFS(graph, V)
for i in result1 :
print(i, end= ' ')
print()
for i in result2 :
print(i, end= ' ')