如何使用节点列表作为输入在有向图中找到连通分量?

Zas*_*asu 4 python graph networkx

我有一个有向图 G,是使用 Python 中的 networkX 创建的。每条边都是双向的。我有一个特定的节点列表,我试图找到这些节点内的连接组件。下面我创建了一个示例数据集(我正在处理的实际图表要大得多)。

import networkx as nx
G = nx.DiGraph()
nodeList = range(1,10)

for i in range (0,len(nodeList)):
    G.add_node(nodeList[i])

o_nodes = [1,1,2,3,3,3,3,4,4,5,5,6,7,7,8,9,9,10]
d_nodes = [8,3,3,1,7,2,4,5,3,4,6,5,3,9,1,7,10,9]

for i in range(0, len(o_nodes)):
    G.add_edge(o_nodes[i], d_nodes[i])  
    
nx.draw(G, with_labels = True)
Run Code Online (Sandbox Code Playgroud)

结果图的图片

假设我有一个节点列表 ,selectNodeList = [1,2,5,6,7,8,9,10]并且我需要找到这些节点内的连接组件。所以,结果我想得到类似的东西[8,1], [7,9,10], [2], [5,6]。我想从选择节点列表中获取覆盖所有节点所需的最小组件数。

我尝试过使用 for 循环,if nx.shortest_path_length(G, source = selectNodeList[i], target = selectNodeList[j]) == 1:然后附加到列表来获取每个节点的直接邻居,但我不确定之后如何到达邻居以及如何创建可读输出。

编辑:这是我在上一部分中提到的代码。我不愿意添加它,因为它还没有完全完成。我的思路是首先获取两个直接邻居的节点,然后搜索另一个也是其中一个节点的直接邻居的节点,依此类推。但是,这不会输出根本未连接的节点,并且会产生一个包含重复连接节点的列表(例如 [1 8 1 8 1 8 5 6 5 6 ...]。对我来说,一个问题是我不我不知道如何处理创建不同维度的输出,也不知道如何在不创建大量 for 循环的情况下解决问题。

connected = []
for i in range(0,34):
    for j in range (1,34):
        if nx.shortest_path_length(G, source = selectNodeList[i], target = selectNodeList[j]) == 1:
            connected.append(selectNodeList[i])
            connected.append(selectNodeList[j])
            for k in range(2,34):
                if nx.shortest_path_length(G, source = selectNodeList[j], target = selectNodeList[k]) == 1:
                    connected.append(selectNodeList[k])
                    for l in range (3,34):
                        if nx.shortest_path_length(G, source = selectNodeList[k], target = selectNodeList[l]) == 1:
                            connected.append(selectNodeList[l])
                            for m in range(4,34):
                                if nx.shortest_path_length(G, source = selectNodeList[l], target = selectNodeList[m]) == 1:
                                    connected.append(selectNodeList[m])
Run Code Online (Sandbox Code Playgroud)

Com*_*tes 5

您需要在节点子集引起的子图中找到连接的组件(弱或强,这并不重要,因为所有边都是双向的)。

node_subset = [1,2,5,6,7,8,9,10]
[list(cc) for cc in nx.strongly_connected_components(G.subgraph(node_subset))]
Run Code Online (Sandbox Code Playgroud)

[[8, 1], [2], [5, 6], [9, 10, 7]]