-
10.1 写出图10.20所示非赋权无向图的关联矩阵和邻接矩阵
-
绘制图
import networkx as nx import pylab as plt import numpy as np A=np.zeros((6,6)) List=[(1,2),(1,4),(2,3),(3,4),(3,5),(3,6),(4,5),(4,6),(5,6)] for i in List: A[i[0]-1,i[1]-1]=1 G=nx.Graph(A) pos=nx.spring_layout(G) nx.draw(G,pos,with_labels=True,font_size=12) plt.show()
-
-
10.2 计算图10.21所示赋权无向图中从 v 1 到 v 5 v_1到v_5 v1到v5的最短路径和最短距离
-
绘制图
import networkx as nx import pylab as plt import numpy as np LIST=[(1,2,7),(1,3,3),(1,4,12),(2,3,3),(2,6,2),(3,4,8),(4,5,1),(5,6,3)] G=nx.Graph() G.add_nodes_from(range(1,7)) G.add_weighted_edges_from(LIST) weight=nx.get_edge_attributes(G,'weight')#获取权重信息 pos=nx.shell_layout(G) nx.draw(G,pos,font_size=12,font_weight='bold',with_labels=True) nx.draw_networkx_edge_labels(G,pos,edge_labels=weight) plt.show()
-
求解任意两点的最短路
distance=dict(nx.shortest_path_length(G,weight='weight')) a=nx.to_numpy_matrix(G) m,n=a.shape for i in range(1,m+1): for j in range(1,n+1): if i!=j: print('{0}到{1}的最短距离为:{2}\n'.format(i, j, distance[i][j]))
-
-
10.3 求图10.21 所示赋权无向图的最小生成树
import networkx as nx import pylab as plt import numpy as np LIST=[(1,2,7),(1,3,3),(1,4,12),(2,3,3),(2,6,2),(3,4,8),(4,5,1),(5,6,3)] G=nx.Graph() G.add_nodes_from(range(1,7)) G.add_weighted_edges_from(LIST) T=nx.minimum_spanning_tree(G)#默认为破圈法 w=nx.get_edge_attributes(T,'weight') print("最小生成树的长度为:",sum(w.values())) nx.draw(T,pos=nx.shell_layout(T),with_labels=True,node_color='blue') nx.draw_networkx_edge_labels(T,pos=nx.shell_layout(T),edge_labels=w) plt.show() #最小生成树的长度为: 12
- 10.4 已知有6个村子,互相间道路的距离如图10.22所示,拟合建一所小学,已知A处有小学生100人,B处80人,C处60 人,D处40人,E处70人,F处90 人。问小学应再建在那个村庄,使学生上学最方便(走的总路程最短)
-
求每个点到其余各点的最短距离矩阵
-
(每个村庄)人数 × \times × 距离=总路程
import networkx as nx import pylab as plt import numpy as np #绘制图 nodes='abcdef'.upper() List=[(1,2,2),(1,3,7),(2,3,4),(2,4,6),(2,5,8),(3,4,1),(3,5,3),(4,5,1),(4,6,6),(5,6,3)] G=nx.Graph() G.add_nodes_from(range(1,7)) G.add_weighted_edges_from(List) w=nx.get_edge_attributes(G,'weight') pos=nx.shell_layout(G) nx.draw(G,pos,node_color='red',labels=dict(zip(range(1,7),list(nodes)))) nx.draw_networkx_edge_labels(G,pos,font_size=10,edge_labels=w) plt.show() #构造最短距离矩阵 distance=nx.shortest_path_length(G,weight='weight') matrix=np.zeros((6,6)) for i in distance: a=i[0]-1 for j in range(1,7): matrix[a][j-1]=i[