#最小生成树MST===================================================
primgraph = mat
chararray = country
charlist = []
charlist.append(chararray[0])
mid = [] # mid[i]表示生成树集合中与点i最近的点的编号
lowcost = [] # lowcost[i]表示生成树集合中与点i最近的点构成的边最小权值 ,-1表示i已经在生成树集合中
lowcost.append(-1)
mid.append(0)
n = len(chararray)
for i in range(1, n): # 初始化mid数组和lowcost数组
lowcost.append(primgraph[0][i])
mid.append(0)
sum = 0
for _ in range(1, n): # 插入n-1个结点
minid = 0
min = MAX
for j in range(1, n): # 寻找每次插入生成树的权值最小的结点
if (lowcost[j] != -1 and lowcost[j] < min):
minid = j
min = lowcost[j]
charlist.append(chararray[minid])
print(chararray[mid[minid]] + '——' + chararray[minid] + '权值:' + str(lowcost[minid]))
sum += min
lowcost[minid] = -1
for j in range(1, n): # 更新插入结点后lowcost数组和mid数组值
if (lowcost[j] != -1 and lowcost[j] > primgraph[minid][j]):
lowcost[j] = primgraph[minid][j]
mid[j] = minid
print("sum=" + str(sum))
print("插入结点顺序:" + str(charlist))
#画图=================================================
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_edge('Germany', 'UK', weight=0.2688021166758405)
G.add_edge('UK', 'France', weight=0.06576401308305482)
G.add_edge('UK', 'Korea', weight=0.24630612660570753)
G.add_edge('Korea', 'US', weight=0.2539864458525312)
G.add_edge('France', 'Singapore', weight=0.27557016110097404)
G.add_edge('France', 'Japan', weight=0.30735759032864995)
G.add_edge('Japan', 'Italy', weight=0.11457281999226256)
G.add_edge('Italy', 'India', weight=0.16127098913551138)
G.add_edge('Japan', 'Sweden', weight=0.2549019922176659)
G.add_edge('Sweden', 'Canada', weight=0.33539598203186216)
G.add_edge('France', 'Spain', weight=0.36426180531160884)
G.add_edge('Singapore', 'Australia', weight=0.3780635013276508)
G.add_edge('US', 'Russia', weight=0.4107432792870739)
G.add_edge('US', 'China', weight=0.47363749762703256)
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_size=5000, node_color='c')
nx.draw_networkx_edges(G, pos, width=8, alpha=0.5, edge_color='k')
nx.draw_networkx_labels(G, pos, font_size=20, font_color='k')
plt.axis('off')
plt.show()