在networkx图中查找孤岛

2024-06-16 12:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在networkx模块中寻找一个函数,它将列出我的图形中的所有孤岛。我找了一会儿,似乎什么也没找到

These are the islands which I am looking to list


Tags: 模块theto函数networkx图形whicham
1条回答
网友
1楼 · 发布于 2024-06-16 12:25:09

使用nx.connected_components(),您可以按如下方式绘制和打印所需的“孤岛”:

import networkx as nx
from matplotlib import pyplot as plt
G = nx.Graph()
G.add_edges_from([(1,2),(2,3),(1,3),(1,4),(5,6),(6,7),(7,8),(8,5),(9,10),(10,11)])
for i, c in enumerate(nx.connected_components(G)):
    print(f"Island {i+1}: {c}")
nx.draw(G, with_labels=True)
plt.show()

#output
Island 1: {1, 2, 3, 4}
Island 2: {8, 5, 6, 7}
Island 3: {9, 10, 11}

enter image description here

相关问题 更多 >