先利用Python的dic建立一个简单的图,再利用队列来实现广度优先的搜索。
代码如下:
from collections import deque
def person_is_Qin(name):
return name == "Qin"
graph = {}
graph["Bobby"] = ["Liu", "Wen", "Ma"]
graph["Liu"] = ["Chen"]
graph["Chen"] = ["Wen"]
graph["Wen"] = ["Tan"]
graph["Ma"] = ["Zhao", "Qin"]
graph["Qin"] = []
graph["Zhao"] = []
graph["Tan"] = []
search_que = deque()
search_que += graph["Bobby"]
flag = 0
while search_que:
person = search_que.popleft()
if person_is_Qin(person):
print("There is a guy named Qin in your relations")
flag = 1
break
else:
search_que += graph[person]
if flag == 0:
print("There isn't any guy name Qin")