##无权无向网络的全局最短路径 import networkx as nx graph1 = nx.Graph() graph1.add_nodes_from([1,2,3,4,5,6]) graph1.add_edges_from([(1,2), (2,3), (5,6), (1,5), (2,4)]) def global_average_shortest_path(Graph): Dict = dict(nx.all_pairs_shortest_path_length(Graph)) length1 = len(Dict.values()) total = 0 edges_number = 0 for sourcenodes in Dict.values(): total = total +sum(sourcenodes.values()) edges_number = edges_number + len(sourcenodes.values()) average_shortest_path = total/(edges_number-length1) return average_shortest_path print(global_average_shortest_path(graph1))
##基于dijkstra算法的无向加权网络全局平均最短路径
import networkx as nx graph1 = nx.Graph() graph1.add_nodes_from([1,2,3,4,5,6]) graph1.add_weighted_edges_from([(1,2,2), (2,3,1), (5,6,2), (1,5,3), (2,4,7)]) def global_average_shortest_path(Graph): Dict = dict(nx.all_pairs_dijkstra_path_length(Graph)) length1 = len(Dict.values()) total = 0 edges_number = 0 for sourcenodes in Dict.values(): total = total +sum(sourcenodes.values()) edges_number = edges_number + len(sourcenodes.values()) average_shortest_path = total/(edges_number-length1) return average_shortest_path print(global_average_shortest_path(graph1))