由于python自带数据结构不含图等数据结构,在使用python构建图需要依赖第三方库networkx,并且需要便准库中的队列来实现广度优先搜索算法。本文原始算法出自《算法图解》,原文通过不断创建字典(散列表)实现图结构,这里依靠第三方库重新实现,可视化及便捷性提高。
import networkx as nx
import matplotlib.pyplot as plt
from collections import deque
def is_salesman(name): # 判断对象是否是售货员
if g.nodes[person]['job'] == 'salesman':
return name
searched = []
g = nx.DiGraph() # 创建有向图
g.add_edges_from([('you', 'bob'), ('you', 'alice'), ('you', 'claire'), ('bob', 'anuj'), ('bob', 'peggy'), ('alice', 'peggy'), ('claire', 'jonny'), ('claire', 'thom'),('anuj', 'kite')])
g.nodes['thom']['job'] = g.nodes['kite']['job'] = 'salesman'
# 创建队列
search_deque = deque()
search_deque += g.neighbors('you')
while search_deque:
person = search_deque.popleft() # 每次从队列取出一个对象
detail = g.nodes[person]
if (not detail) == False and person not in searched:
# 判断职业是否是销售员
if is_salesman(person):
print('The closest candidate is: '+person)
break
else:
searched.append(person)
search_deque += g.neighbors(person)
my_pos = nx.spring_layout(g, seed=11)
nx.draw(g, pos=my_pos, with_labels=True, font_weight='bold')
plt.show()