在 networkx 图中查找岛屿
Finding islands in a networkx graph
我正在 networkx 模块中寻找一个函数,它会列出我图表中的所有岛屿。找了半天,好像没找到。
These are the islands which I am looking to list
使用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}
我正在 networkx 模块中寻找一个函数,它会列出我图表中的所有岛屿。找了半天,好像没找到。
These are the islands which I am looking to list
使用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}