在这个答案中提到的思路,我们可以遍历连接组件的combinations
,并连接两个随机节点。采用combinations
的优点在于我们只需要一次遍历组件,并确保在每次迭代时忽略之前看到的组件,因为在combinations
中,顺序不重要,也就是说如果我们看到了组合(1,2)
,那么我们就不会再看到(2,1)
,这可能会导致通过两个不同的节点连接两个组件,从而使它们与图的其余部分隔离开来。
因此,使用您示例的简化版本:
G = nx.fast_gnp_random_graph(100,0.02,seed=1)
plt.figure(figsize=(12,6))
nx.draw(G, node_size=100, node_color='lightgreen')
![enter image description here](https://istack.dev59.com/cfatd.webp)
import random
from itertools import combinations, groupby
components = dict(enumerate(nx.connected_components(G)))
components_combs = combinations(components.keys(), r=2)
for _, node_edges in groupby(components_combs, key=lambda x: x[0]):
node_edges = list(node_edges)
random_comps = random.choice(node_edges)
source = random.choice(list(components[random_comps[0]]))
target = random.choice(list(components[random_comps[1]]))
G.add_edge(source, target)
plt.figure(figsize=(12,6))
nx.draw(G, node_size=100, node_color='lightgreen')
![enter image description here](https://istack.dev59.com/Ww1GY.webp)