首页 > 其他 > 详细

BFS & DFS

时间:2020-05-03 18:03:47      阅读:31      评论:0      收藏:0      [点我收藏+]
 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)

 

BFS & DFS

原文:https://www.cnblogs.com/Halo-zyh-Go/p/12822559.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!