BFS & DFS

 1 graph = {
 2     'A':['B','C'],
 3     'B':['A','C','D'],
 4     'C':['A','B','D','E'],
 5     'D':['B','C','E','F'],
 6     'E':['C','D'],
 7     'F':['D']
 8 }
 9 def BFS(graph,start):
10     queue = []
11     queue.append(start)
12     seen = set()       #使用集合的效率要比使用list的效率高
13     seen.add(start)
14     while len(queue)>0:     #queue不为空的时候
15         vertex = queue.pop(0)
16         next_nodes = graph[vertex]
17         for w in next_nodes:
18             if w not in seen:
19                 queue.append(w)
20                 seen.add(w)     #将见过的添加进去
21         print(vertex)
22 def DFS(graph,start):
23     stack = []
24     stack.append(start)
25     seen = set()       #使用集合的效率要比使用list的效率高
26     seen.add(start)
27     while len(stack)>0:     #stack不为空的时候
28         vertex = stack.pop()        #由于是栈所以弹出最后一个元素
29         next_nodes = graph[vertex]
30         for w in next_nodes:
31             if w not in seen:
32                 stack.append(w)
33                 seen.add(w)     #将见过的添加进去
34         print(vertex)
35 print('BFS')
36 BFS(graph,'E')
37 print('*'*100)
38 print('DFS')
39 DFS(graph,'E')

猜你喜欢

转载自www.cnblogs.com/Halo-zyh-Go/p/12822559.html