Assuming the graph is not oriented, there is a built-in networkx command for this:
node_connected_component(G, n)
The documentation is here . It returns all nodes in the associated component G containing n .
This is not recursive, but I donβt think you really need or even need this.
comments on your code . You have a bug that often leads to infinite recursion. If u and v are neighbors with a power of at least 2, then it will start with u , put v in the list and, when processing v put u in the list and keep repeating. It should only be changed to handle neighbors that are not in neighbors_list . It's expensive to check, so use a kit instead. There is also a small problem if the starting node has degree 1. Your test for degree 1 does not do what you need. If the initial node has degree 1, but its neighbor has a higher degree, it will not find neighboring neighbors.
Here you can change the code:
def fetch_connected_nodes(G, node, seen = None): if seen == None: seen = set([node]) for neighbor in G.neighbors(node): print(neighbor) if neighbor not in seen: seen.add(neighbor) fetch_connected_nodes(G, neighbor, seen) return seen
You name it as fetch_connected_nodes(assembly, starting_node) .
source share