-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfsbfs.py
55 lines (48 loc) · 1.19 KB
/
dfsbfs.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
from collections import deque
N, M, V = map(int, input().split())
def DFS(edges, start):
visited = [False] * (N + 1)
visited[0] = True
Q = deque()
Q.append(start)
while Q:
now = Q.popleft()
if visited[now]:
continue
visited[now] = True
print(now, end=" ")
canGo = []
for edge in edges:
if edge[0] == now:
canGo.append(edge[1])
if edge[1] == now:
canGo.append(edge[0])
canGo.sort(reverse=True)
Q.extendleft(canGo)
print()
def BFS(edges, start):
visited = [False] * (N + 1)
visited[0] = True
Q = deque()
Q.append(start)
while Q:
now = Q.popleft()
if visited[now]:
continue
visited[now] = True
print(now, end=" ")
canGo = []
for edge in edges:
if edge[0] == now:
canGo.append(edge[1])
if edge[1] == now:
canGo.append(edge[0])
canGo.sort()
for dest in canGo:
Q.append(dest)
edges = []
for i in range(M):
a, b = map(int, input().split())
edges.append((a, b))
DFS(edges, V)
BFS(edges, V)