from collections import deque
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"] = []
def person_is_seller(a):
return a[-1] == 'm'
def search(name):
search_queue = deque() #创建队列
search_queue += graph[name]
searched = []
while search_queue:
person = search_queue.popleft() #将队列第一位取出
if person not in searched: #将已查过的人跳过去
if person_is_seller(person):
print (person + " is a mango seller!")
return True
else:
search_queue += graph[person] # 将此人关联的其他人加入队列
searched.append(person)
return False
search("you") # -->thom is a mango seller!
python实现广度优先查找
最新推荐文章于 2024-01-10 13:22:57 发布
本文介绍了一个简单的搜索算法,用于在一个社交图谱中寻找特定条件下的芒果销售者。通过队列实现广度优先搜索,该算法从指定的起点出发,逐步遍历其邻居节点,直至找到符合条件的目标人物。
875

被折叠的 条评论
为什么被折叠?



