8-13、广度优先搜索
1、广度优先搜索,用于图的查找算法,解决两个问题:
从节点A出发,有前往节点B的路径吗?
从节点A出发,前往节点B的哪条路径最短?
graph = {} graph["you"] = ["alice", "bob", "claire"] graph["bob"] = ["anuj", "peggy"] graph["alice"] = ["peggy"] graph["claire"] = ["thom", "jonny"] graph["anuj"] = [] graph["peggy"] = [] graph["thom"] = [] graph["jonny"] = [] from collections import deque search_queue = deque() search_queue += graph["you"] def person_is_seller(name): return name[-1] == 'm' def search(name): search_queue = deque() search_queue += graph[name] searched = [] while search_queue:##只要队列不为空 person = search_queue.popleft() if not person in searched:##仅当这个人没检查过时才检查 if person_is_seller(person): print (person + "is a mango seller!") return True else : search_queue += graph[person] search.append(person)##将这个人标记为检查过,否则可能导致无限循环 return False search("you")
结果:
找到了最后一个字符为m的人。
1、用散列表可以表示图的链接关系。
本文来自博客园,作者:hematologist,转载请注明原文链接:https://www.cnblogs.com/littleMa/p/9471798.html
posted on 2018-08-13 23:43 hematologist 阅读(174) 评论(0) 编辑 收藏 举报