标签:注意 最小 raw pat def mic print rom 最短路
图2和图3都是树,但是图3是最小生成树,他的路径之和更小
代码
import networkx as nx import matplotlib.pyplot as plt tupo=[[0,2,2,0,3,0], [2,0,5,1,4,0], [2,5,0,2,6,4], [0,1,2,0,0,3], [3,4,6,0,0,0], [0,0,4,3,0,0]] def circle(tupo,st): result=[] def trace(path,tupo,now): if len(result)==1:return if now==st and len(path)>2: result.append(list(path)) return for i in range(len(tupo)): if tupo[now][i]==0 or i in path:continue path.append(i) trace(path,tupo,i) path.pop() trace([],tupo,st) if len(result)!=0: result[0].insert(0,st) return result[0] return result def des_cir(tupo,st): n=len(tupo) for i in range(n): while(1): res=[] res=circle(tupo,st) if len(res)==0:break mid_len=0 mid_st=-1 for j in range(len(res)-1): if tupo[res[j]][res[j+1]]>mid_len or (tupo[res[j]][res[j+1]]==mid_len and res[j]+res[j+1]>res[mid_st]+res[mid_st+1]): mid_len=tupo[res[j]][res[j+1]] mid_st=j tupo[res[mid_st]][res[mid_st+1]]=tupo[res[mid_st+1]][res[mid_st]]=0 for item in tupo: print(item) des_cir(tupo,0) def draw(tupo): nodes=[ ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘] G=nx.Graph() for node in nodes: G.add_node(node) edges=[] for i in range(len(tupo)): for j in range(len(tupo)): if tupo[i][j]!=0: edges.append((nodes[i],nodes[j])) r=G.add_edges_from(edges) nx.draw(G, with_labels=True,node_color=‘y‘,) plt.show() draw(tupo)
效果图
注意的是,最小生成树与最短路径是不一样的
最小生成树只能保证路径之和最小而不能保证任意两点之间路径最小
如上图1拓扑,最小生成树图2的A到D是7,2跳
最短路径A到D是6,1跳
END
标签:注意 最小 raw pat def mic print rom 最短路
原文地址:https://www.cnblogs.com/ljy1227476113/p/13382982.html