已知图的所有节点和边连接关系,如下图,求指定两节点的最短路径和距离
import networkx as nx
import pylab
nodes = [('B','D'), ('D','E'), ('D','A'), ('E','A'), ('E','C'), ('A','C')]
graph = nx.Graph(nodes)
nx.draw(graph, node_color = 'red', with_labels = True)
dist = nx.shortest_path(graph, 'A', 'A')
print(f"A-A的路径:{dist},距离:{len(dist)}")
dist = nx.shortest_path(graph, 'A', 'B')
print(f"A-B的路径:{dist},距离:{len(dist)}")
dist = nx.shortest_path(graph, 'A', 'C')
print(f"A-C的路径:{dist},距离:{len(dist)}")
dist = nx.shortest_path(graph, 'A', 'D')
print(f"A-D的路径:{dist},距离:{len(dist)}")
dist = nx.shortest_path(graph, 'A', 'E')
print(f"A-E的路径:{dist},距离:{len(dist)}")
dist = nx.shortest_path(graph, 'B', 'C')
print(f"B-C的路径:{dist},距离:{len(dist)}")
pylab.show()
运行结果:
A-A的路径:[‘A’],距离:1
A-B的路径:[‘A’, ‘D’, ‘B’],距离:3
A-C的路径:[‘A’, ‘C’],距离:2
A-D的路径:[‘A’, ‘D’],距离:2
A-E的路径:[‘A’, ‘E’],距离:2
B-C的路径:[‘B’, ‘D’, ‘E’, ‘C’],距离:4
- 如果是有向图,上面使用nx.DiGraph(nodes)
- 有向图的路径是按方向进行的,如果方向走不到,则会报错