让我为您提供解决您的任务的 python networkX 代码:
import networkx as nx
import matplotlib.pyplot as plt#for the purpose of drawing the graphs
DG=nx.DiGraph()
DG.add_edges_from([(3,8),(3,10),(5,11),(7,11),(7,8),(11,2),(11,9),(11,10),(8,9)])
DG.remove_node(11)
connected_components 方法令人惊讶地不适用于有向图,因此我们将图变为无向图,找出未连接的节点,然后将它们从有向图中删除
UG=DG.to_undirected()
not_connected_nodes=[]
for component in nx.connected_components(UG):
if len(component)==1:#if it's not connected, there's only one node inside
not_connected_nodes.append(component[0])
for node in not_connected_nodes:
DG.remove_node(node)#delete non-connected nodes
如果要查看结果,请在脚本中添加以下两行:
nx.draw(DG)
plt.show()