-
Notifications
You must be signed in to change notification settings - Fork 0
/
1260.py
62 lines (48 loc) · 1.39 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import sys
from collections import deque
def dfs(graph, start):
stack = [start]
visited = [start]
while stack:
num = stack[-1]
visitcheck = list(set(graph[num]) - set(visited))
visitcheck.sort()
if visitcheck:
stack.append(visitcheck[0])
visited.append(visitcheck[0])
else:
#print(stack)
stack.pop()
for i in range(len(visited)):
print(visited[i], end = " ")
print()
return None
def bfs(graph, start):
queue = deque([start])
visited = [start]
while queue:
num = queue[0]
visitcheck = list(set(graph[num]) - set(visited))
visitcheck.sort()
if visitcheck:
for i in range(len(visitcheck)):
queue.append(visitcheck[i])
visited.append(visitcheck[i])
queue.popleft()
else:
queue.popleft()
for i in range(len(visited)):
print(visited[i], end = " ")
print()
return None
if __name__ == "__main__":
n, m, v = map(int, sys.stdin.readline().split())
graph = {x+1: [] for x in range(n)}
for _ in range(m):
a, b = map(int, sys.stdin.readline().split())
graph[a].append(b)
graph[b].append(a)
for i in range(1, n+1):
graph[i].sort()
dfs(graph, v)
bfs(graph, v)