官方文档:
https://networkx.github.io/documentation/networkx-1.10/reference/algorithms.html
最短路:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
#G.add_node(1) #添加一个节点1
#G.add_edge(2,3,10) #添加一条边2-3(隐含着添加了两个节点2、3)
#G.add_edge(3,2) #对于无向图,边3-2与边2-3被认为是一条边
#G.add_weighted_edges_from([(1,2,8)])
#G.add_weighted_edges_from([(1,3,10)])
#G.add_weighted_edges_from([(2,3,6)])
G.add_edge('A', 'B', weight=4)
G.add_edge('B', 'D', weight=2)
G.add_edge('A', 'C', weight=3)
G.add_edge('C', 'D', weight=5)
G.add_edge('A', 'D', weight=6)
G.add_edge('C', 'F', weight=7)
G.add_edge('A', 'G', weight=1)
G.add_edge('H', 'B', weight=2)
for u,v,d in G.edges(data=True):
print(u,v,d['weight'])
edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)])
#fixed_position = {'A':[ 1., 2.],
# 'B': [ 1., 0.],
# 'D': [ 5., 5.],
# 'C': [ 0.,6.]}#每个点在坐标轴中的位置
#pos=nx.spring_layout(G,pos = fixed_position)#获取结点的位置,每次点的位置都是随机的
pos = nx.spring_layout(G) #也可以不固定点
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels,font_size=14)#绘制图中边的权重
print(edge_labels)
print("nodes:", G.nodes()) #输出全部的节点: [1, 2, 3]
print("edges:", G.edges()) #输出全部的边:[(2, 3)]
print("number of edges:", G.number_of_edges()) #输出边的数量
nx.draw_networkx(G,pos,node_size=400)
plt.savefig("wuxiangtu.png")
plt.show()
# 计算两点间的最短路
# dijkstra_path
print('dijkstra方法寻找最短路径:')
path=nx.dijkstra_path(G, source='H', target='F')
print('节点H到F的路径:', path)
print('dijkstra方法寻找最短距离:')
distance=nx.dijkstra_path_length(G, source='H', target='F')
print('节点H到F的距离为:', distance)
# 一点到所有点的最短路
p=nx.shortest_path(G,source='H') # target not specified
d=nx.shortest_path_length(G,source='H')
for node in G.nodes():
print("H 到",node,"的最短路径为:",p[node])
print("H 到",node,"的最短距离为:",d[node])
# 所有点到一点的最短距离
p=nx.shortest_path(G,target='H') # target not specified
d=nx.shortest_path_length(G,target='H')
for node in G.nodes():
print(node,"到 H 的最短路径为:",p[node])
print(node,"到 H 的最短距离为:",d[node])
# 任意两点间的最短距离
p=nx.shortest_path_length(G)
p=dict(p)
d=nx.shortest_path_length(G)
d=dict(d)
for node1 in G.nodes():
for node2 in G.nodes():
print(node1,"到",node2,"的最短距离为:",d[node1][node2])