-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0707_DFSBFS.py
More file actions
71 lines (40 loc) · 1.04 KB
/
Copy path0707_DFSBFS.py
File metadata and controls
71 lines (40 loc) · 1.04 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
52
53
54
55
56
import sys
N, nl, st =map(int, sys.stdin.readline().split())
graph={i:[] for i in range(N)}
for i in range(nl):
I=tuple(map(int, sys.stdin.readline().split()))
for i in I:
if i not in graph.keys():
graph[i] =[]
graph[I[0]].append(I[1])
if I[0] not in graph[I[1]]:
graph[I[1]].append(I[0])
graph[I[0]].sort()
def DFS(graph, s):
visited=[]
def DFS_visited(graph, visted, s):
visted.append(s)
for i in graph[s]:
if i not in visted:
DFS_visited(graph, visited, i)
DFS_visited(graph, visited, s)
a = ''
for i in visited:
a += str(i) + ' '
print(a[:-1])
return
from collections import deque
def BFS(graph, root):
visited = []
queue = deque([root])
while queue:
n = queue.popleft()
if n not in visited:
visited.append(n)
queue += graph[n] - set(visited)
a = ''
for i in visited:
a += str(i) + ' '
print(a[:-1])
DFS(graph, st)
BFS(graph, st)