How to find all connected subgraph of a graph in networkx?

我的梦境 提交于 2020-07-18 21:06:43

问题


I'm developing a python application, and i want to list all possible connected subgraph of any size and starting from every node using NetworkX.

I just tried using combinations() from itertools library to find all possible combination of nodes but it is very too slow because it searchs also for not connected nodes:

for r in range(0,NumberOfNodes)
for SG in (G.subgraph(s) for s in combinations(G,r):
    if (nx.is_connected(SG)):
        nx.draw(SG,with_labels=True)
        plt.show()

The actual output is correct. But i need another way faster to do this, because all combinations of nodes with a graph of 50 nodes and 8 as LenghtTupleToFind are up to 1 billion (n! / r! / (n-r)!) but only a minimal part of them are connected subgraph so are what i am interested in. So, it's possible to have a function for do this?

Sorry for my english, thank you in advance

EDIT:

This is an example:

example of starting graph

so, the results i would like to have:

[0]
[0,1]
[0,2]
[0,3]
[0,1,4]
[0,2,5]
[0,2,5,4]
[0,1,4,5]
[0,1,2,4,5]
[0,1,2,3]
[0,1,2,3,5]
[0,1,2,3,4]
[0,1,2,3,4,5]
[0,3,2]
[0,3,1]
[0,3,2]
[0,1,4,2]

and all combination that generates a connected graph


回答1:


I had the same requirements and ended up using this code, super close to what you were doing. This code yields exactly the input you asked for.

import networkx as nx
import itertools

G = you_graph
all_connected_subgraphs = []

# here we ask for all connected subgraphs that have at least 2 nodes AND have less nodes than the input graph
for nb_nodes in range(2, G.number_of_nodes()):
    for SG in (G.subgraph(selected_nodes) for selected_nodes in itertools.combinations(G, nb_nodes)):
        if nx.is_connected(SG):
            print(SG.nodes)
            all_connected_subgraphs.append(SG)



回答2:


You can find all the connected components in O(n) time and memory complexity. Keep a seen boolean array, and run Depth First Search (DFS) or Bread First Search (BFS), to find the connected components.
In my code, I used DFS to find the connected components.

seen = [False] * num_nodes
def search(node):
    component.append(node)
    seen[node] = True
    for neigh in G.neighbors(node):
        if not seen[neigh]:
            dfs(neigh)

all_subgraphs = []    

# Assuming nodes are numbered 0, 1, ..., num_nodes - 1
for node in range(num_nodes):
    component = []
    dfs(node)
    # Here `component` contains nodes in a connected component of G
    plot_graph(component)  # or do anything
    all_subgraphs.append(component)


来源:https://stackoverflow.com/questions/54440779/how-to-find-all-connected-subgraph-of-a-graph-in-networkx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!