广度优先搜索

 

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(name):
  return name[-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]  # 如果不是芒果商,这个人的朋友都加入搜索队列

    return False  # 运行到这里则说明没有芒果商人


search("you")

 

posted @ 2020-04-02 10:19  1101011  阅读(110)  评论(0)    收藏  举报