最小生成树和最短路径

pull/2/head
盘荣博 4 months ago
parent 7d1020b93a
commit 19262e6ef2

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

@ -0,0 +1,28 @@
import networkx as nx
import pylab as plt
import numpy as np
p=[25,26,28,31] ;a=[10,14,18,26] ; r=[20,16,13,11]
b= np.zeros((5,5))
for i in range(5):
for j in range(i+1,5):
b[i,j]=p[i]+np.sum(a[0:j-i])-r[j-i-1]
G=nx.DiGraph(b)
print(G)
p=nx.dijkstra_path(G,source=0,target=4,weight='weight')
print("最短路径为:",np.array(p)+1)#下标从零开始
d=nx.dijkstra_path_length(G,source=0,target=4,weight="weight")
print("所求的费用最小值为:",d)
s=dict(zip(range(5),range(1,6)))
plt.rc("font",size=16)
pos=nx.shell_layout((G))#设置布局
print(type(pos),'\npos=',pos)
w=nx.get_edge_attributes(G,"weight")
print(type(w),'\nw=',w)
nx.draw(G,pos,font_weight='bold',labels=s,node_color='r')#绘制点和边
nx.draw_networkx_edge_labels(G,pos,edge_labels=w)#绘制标签
#绘制最短路径
path_edges=list(zip(p,p[1:]))
print(type(path_edges),"\npath_edges=",path_edges)
nx.draw_networkx_edges(G,pos,edgelist=path_edges,edge_color="r",width=1)
plt.savefig("figure10_9.png");plt.show()
Loading…
Cancel
Save