美文网首页
python实现广度优先查找

python实现广度优先查找

作者: yytester | 来源:发表于2018-07-18 16:37 被阅读111次
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实现广度优先查找

      本文链接:https://www.haomeiwen.com/subject/xotapftx.html