如何在图表中显示直径?

问题描述

我有一个包含 5 个节点的完整图 G,我必须找到 G(随机选择的节点)的直径,并将该直径绘制为红色。我怎样才能用 Networkx 和 Python 做到这一点?这些是我的尝试。此外,我需要说它们更多,但唯一的区别是我尝试使用其他函数(子图、算法等)而不是最短路径。此外,我需要解释一下随机节点意味着您为直径随机

import networkx as nx  #1 attempt

G = nx.complete_graph(5)

dg = nx.shortest_path(G)

edge_colors = ['red' if e in dg.edges else 'black' for e in G.edges]

nx.draw(G,edge_color=edge_colors)






def get_diameters(graph):   #attempt 2


diams = []
for g in nx.connected_component_subgraphs(graph):
    diams.append(nx.diameter(g))
diams = list(filter(lambda a: a != 0,diams))
return np.array(diams) Graph.number_of_nodes()

解决方法

据我了解您的问题,您不是在寻找图形本身的直径,而是在给定随机起始节点的图形中寻找最长最短路径。这可以通过使用带有 nx.shortest_path 关键字参数的 source 来实现,给它一个随机的起始节点。我们可以查看结果字典,找到最长最短路径,并用红色绘制形成这条路径的边。

代码

import networkx as nx
import random

# Create graph
G = nx.fast_gnp_random_graph(10,0.3)

# Pick a random node
source = random.choice(list(G.nodes))

# Find the longest shortest path from the node
shortest_paths = nx.shortest_path(G,source=source)
target = max(shortest_paths,key=lambda i: len(shortest_paths[i]))
l_s_path = shortest_paths[target]
l_s_path_edges = list(zip(l_s_path,l_s_path[1:]))

# Draw the graph,then draw over the required edges in red.
pos = nx.spring_layout(G)
nx.draw(G,pos=pos,with_labels=True)
nx.draw_networkx_edges(G,edge_color='r',edgelist=l_s_path_edges,pos=pos)

输出

注意在这个例子中,图的直径是4;最长最短路径是从节点 6 到节点 4。随机选择的源节点为 7 - 从节点 7 开始的最长最短路径长度为 3。

enter image description here