Let's say we have the following graph (please see below):
import networkx as nx
G = nx.Graph()
G.add_edges_from([(1,2), (2,3), (1,3), (3,4), (4,5), (5,6), (6,10), (10,11), (5,7), (5,8), (8,9), (9,10)])
At one moment there is a subgraph that consists of few interconnected nodes and one node that has no edges:
nx.draw(G.subgraph([1,2,3,11]), with_labels=True)
Since all nodes of the incomplete subgraph come from the same full graph they can be connected (e.g. by a shortpath) what is presented on the following picture:
nx.draw(G.subgraph([1,2,3,4,5,6,10,11]), with_labels=True)
I wonder whether there is a networkx function that given a set (or any iterable of nodes) returns a subgraph that makes sure all nodes are connected. In other words (and case-specifically) I would like to get the list [1,2,3,4,5,6,10,11] as an output of a function.
Clarification edit
Since it seems that I'm being misunderstood I'm giving few more examples.
First example
G1 = nx.Graph()
G1.add_edges_from([(1,2), (1,3), (2,3), (2,4), (3,4), (4,5), (5,6), (6,7), (5,7), (5,8), (8,9), (9,10), (10,12), (10,11), (11,12)])
chosen_nodes = [1,2,3,12] # construct a subgraph based on those nodes
output_nodes = [1,2,3,4,5,8,9,10,12]
Output nodes are those nodes that make the subgraph connected, i.e. there are no loose ends in the subgraph.
Second example
G2 = nx.Graph()
G2.add_edges_from([(1,2), (2,3), (3,4), (4,5), (5,6), (4,6)])
chosen_nodes = [1,2,5]
output_nodes = [1,2,3,4,5]
Example 3
G3 = nx.Graph()
G3.add_edges_from([(1,2), (2,3), (3,5), (2,4), (4,5)])
chosen_nodes = [1,2,3]
output_nodes = [1,2,3]
In general there's is a function that based on chosen_nodes creates a subgraph in which all nodes are somehow connected (edges are taken from graph).
def get_connected_subgraph(graph, chosen_nodes):
return output_nodes



g,networkx.connected_components(g)with return an iterator of all connected components, largest component first. - Paul Brodersennetworkx.connected_components(G)returns a generator with only one element (I can usenext()only once thenIterationErroris raised). This element consists of all the nodes inG. The output should be the subset of those elements. - balkon16connected_componentson your subgraph or the original graph? - Paul Brodersenconnected_componentson the original graph. Calling it on a subgraph results in a generator with two elements:[{11}, {1,2,3}]. - balkon16