BFS:队

graph = {
"A" : ["B","C"],
"B" : ["A","C","D"],
"C" : ["A","B","D","E"],
"D" : ["B","C","E","F"],
"E" : ["C","D"],
"F" : ["D"]
}
def BFS(graph, s):
queue = []
queue.append(s) # 向list添加元素,用append()
seen = set() # 此处为set, python里set用的是hash table, 搜索时比数组要快。
seen.add(s) # 向set添加函数,用add()
while (len(queue) > 0):
vertex = queue.pop(0) #提取队头
nodes = graph[vertex] #获得队头元素的邻接元素
for w in nodes:
if w not in seen:
queue.append(w) #将没有遍历过的子节点入队
seen.add(w) #标记好已遍历
print("当前出队的是:",vertex) BFS(graph, 'A')


DFS:栈

graph = {
"A" : ["B","C"],
"B" : ["A","C","D"],
"C" : ["A","B","D","E"],
"D" : ["B","C","E","F"],
"E" : ["C","D"],
"F" : ["D"]
}
def DFS(graph, s):
stack=[]
stack.append(s) # 向list添加元素,用append()
seen = set() # 此处为set, python里set用的是hash table, 搜索时比数组要快。
seen.add(s) # 向set添加函数,用add()
while (len(stack) > 0):
vertex = stack.pop() # 弹出最后一个元素
nodes = graph[vertex]
for w in nodes:
if w not in seen:
stack.append(w)
seen.add(w)
print("当前出栈的是",vertex)
DFS(graph, 'A')


BFS:求最短路

def BFS2(graph, s):
queue = []
queue.append(s)
seen = set()
seen.add(s)
parent = {s:None} #记录一下父子节点这样方便求最短路
while (len(queue) > 0):
vertex = queue.pop(0)
nodes = graph[vertex]
for w in nodes:
if w not in seen:
queue.append(w)
seen.add(w)
parent[w] = vertex
print("当前出队的是:",vertex)
return parent parent = BFS2(graph, 'A')
print("父子表:")
for son in parent:
print(parent[son],son)
print('F->A的最短路:')
start = 'F'
while start:
print(start,end='->')
start= parent[start]
print('EDN')


谢谢灯神的讲解,豁然开朗啊喂 :https://www.bilibili.com/video/av25763384/?spm_id_from=333.788.b_7265636f5f6c697374.2

最新文章

  1. ABP理论学习之工作单元(Unit of Work)
  2. 解决JS加载速度慢
  3. UITableView
  4. java打包遇到问题java.io.IOException: invalid header field
  5. NABCD模型进行竞争性需求分析
  6. 可输入自动匹配Select——jquery ui autocomplete
  7. redis参考
  8. CCNA CCNP CCIE所有实验名称完整版
  9. jquery中get传输方法实现读取xml文件
  10. TreeSet集合排序方式一:自然排序Comparable
  11. Oracle存储过程跨用户执行查询报错
  12. Linux下chkconfig命令
  13. Fantacy团队周二站立会议
  14. discuz 文件模板edit
  15. PAT甲题题解-1036. Boys vs Girls (25)-找最大最小,大水题
  16. delphi 启动停止windows服务 转
  17. 0ctf2017-pages-choices
  18. 【Web学习笔记】浅析CGI概念及用法
  19. main方法为什么是静态的
  20. Java中静态变量、静态代码块、非静态代码块以及静态方法的加载顺序

热门文章

  1. cron 定时任两种配置方式
  2. 深入理解DiscoveryClient
  3. 前缀和序列 & 差分序列
  4. Ecshop 商品详情页如何添加立即购买按钮
  5. python学习第四天基本数据类型 int,string,bool
  6. ecshop 广告调用的几种方式
  7. CodeForces 295B Greg and Graph (floyd+离线)
  8. antd desgin vue 报错 Warning: Each record in table should have a unique `key` prop,or set `rowKey` to an unique primary key.
  9. PHP内置函数parse_str会自动进行urldecode(URL解码)
  10. 导入excle到服务器时候删除服务器历史数据