- 课本上的是手动造轮子,尽管不完善,但是挺好用。这里就不记录课本上的了,通俗易懂,我们主要看看用库函数实现课本上的这俩功能,开阔下思路。
- 主要用到了网络分析库和绘图库,看代码:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
nodes = ['s', 'a', 'z', 'x', 'd', 'c', 'f', 'v']
G.add_nodes_from(nodes)
ebunch = [('a', 'z'), ('a', 's'), ('s', 'x'), ('x', 'd'),
('d', 'c'), ('x', 'c'), ('d', 'f'), ('c', 'f'),
('c', 'v'), ('f', 'v')]
G.add_edges_from(ebunch)
nx.draw(G, pos=nx.spring_layout(G), with_labels=True, font_size=24, node_size=2640)
plt.show()
print(nx.bfs_predecessors(G, 's'))
print(nx.shortest_path(G, 's'))
- 打印出来的结果,看下图和课本图7.4即可,我们这里稍微解释下输出,和课本上的类似:

{'a': 's', 'c': 'x', 'd': 'x', 'f': 'c', 'v': 'c', 'x': 's', 'z': 'a'}
{'a': ['s', 'a'], 'c': ['s', 'x', 'c'], 'd': ['s', 'x', 'd'], 'f': ['s', 'x', 'c', 'f'], 's': ['s'], 'v': ['s'