如何解决networkx:直径给13想找到那些节点或距离是什么
我想找到最远的节点。我使用了直径,它给了我一个整数值,我该怎么做才能在直径的起点和终点获得这些点? 即通过使用某些函数找到图形中最远的点。
解决方法
nx.diameter
似乎只是找到节点之间最长的最短路径的距离,而networkx.algorithms.distance_measures
(docs)模块中的内置函数似乎都无法计算出重新寻找。要获得最远的节点,一种选择是使用对nx.single_source_shortest_path_length(G,n)
的一系列调用,其中G
是图形,n
是源节点。这将返回从n
到G
中所有节点的最短路径的长度,作为由节点键入的dict,值是从节点到源节点n
的距离。然后,您可以浏览这些命令,以找出哪些节点对具有最长的长度。这样的事情应该起作用。
def get_furthest_nodes(G):
sp_length = {} # dict containing shortest path distances for each pair of nodes
diameter = None # will contain the graphs diameter (length of longest shortest path)
furthest_node_list = [] # will contain list of tuple of nodes with shortest path equal to diameter
for node in G.nodes:
# Get the shortest path from node to all other nodes
sp_length[node] = nx.single_source_shortest_path_length(G,node)
longest_path = max(sp_length[node].values()) # get length of furthest node from node
# Update diameter when necessary (on first iteration and when we find a longer one)
if diameter == None:
diameter = longest_path # set the first diameter
# update the list of tuples of furthest nodes if we have a best diameter
if longest_path >= diameter:
diameter = longest_path
# a list of tuples containing
# the current node and the nodes furthest from it
node_longest_paths = [(node,other_node)
for other_node in sp_length[node].keys()
if sp_length[node][other_node] == longest_path]
if longest_path > diameter:
# This is better than the previous diameter
# so replace the list of tuples of diameter nodes with this nodes
# tuple of furthest nodes
furthest_node_list = node_longest_paths
else: # this is equal to the current diameter
# add this nodes tuple of furthest nodes to the current list
furthest_node_list = furthest_node_list + node_longest_paths
# return the diameter,# all pairs of nodes with shortest path length equal to the diameter
# the dict of all-node shortest paths
return({'diameter':diameter,'furthest_node_list':furthest_node_list,'node_shortest_path_dicts':sp_length})
请注意,此解决方案假定图形已连接(对于有向图,已牢固连接),这是您应该使用的,因为使用nx.diameter
可以得到直径的解决方案。这应该与调用diamater的运行时间类似,因为该函数执行相似的步骤,只是不保留导致直径的所有路径链接和节点。请注意,返回字典中的furthest_node_list
项将使每对节点在相反方向上出现两次(如果节点a
和b
的最短路径等于直径,则两个{{1 }}和(a,b)
将在列表中。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。