python通过队列实现广度优先搜索

需求:找名字以m结尾的人,直到找到为止

虚拟出这个场景:

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

# 找人名m结尾的人
def person_is_seller(name):
    return name[-1] == "m"


def main():
    #创建一个队列
    search_queue = deque()
    #将你的邻居加到这个队列中
    search_queue += graph['you']
    # 这个数据用于记录检查过的人
    searched = []
    #只要队列不为空,就取出第一个人
    while search_queue:
        person = search_queue.popleft()
        #当这个人没被检查过才检查
        if not person in searched:
            if person_is_seller(person):
                print(person + "是你要找的人")
                return True
            else:
                search_queue += graph[person]
                #检查过扔到list中
                searched.append(person)
    return False

if __name__ == '__main__':
    main()

你可能感兴趣的:(python通过队列实现广度优先搜索)