Sub topic 14
Using NetworkX for Connected Components
The earlier chapters built BFS, iterative DFS, union-find, and Kosaraju's algorithm by hand. In production code you will usually call a library instead. NetworkX is the standard pure-Python graph library, and it provides each of those operations as a single function.
This chapter assumes you have read the earlier chapters on undirected components, weakly connected components, and strongly connected components. It also assumes you can install packages with pip install networkx.
The Core Functions
NetworkX graphs come in two main classes. nx.Graph is undirected and nx.DiGraph is directed. The component functions return generators, and each generator yields one component as a Python set of nodes.
import networkx as nx
G = nx.Graph()
G.add_edges_from([(0, 1), (1, 2), (3, 4)])
G.add_node(5)
print([sorted(c) for c in nx.connected_components(G)])
# [[0, 1, 2], [3, 4], [5]]
print(nx.number_connected_components(G))
# 3
D = nx.DiGraph([(0, 1), (1, 2), (2, 0), (2, 3)])
print(sorted(sorted(c) for c in nx.strongly_connected_components(D)))
# [[0, 1, 2], [3]]
print(sorted(sorted(c) for c in nx.weakly_connected_components(D)))
# [[0, 1, 2, 3]]Node 5 has no edges, so it needs add_node. A node that only appears in an edge list is added automatically, but an isolated vertex is not part of any edge, so you have to add it yourself. If you leave it out, NetworkX counts one component fewer than the hand-written versions, which loop over range(n).
The table below maps the hand-written code from earlier chapters to the NetworkX call that does the same job.
| Task | Earlier chapter | NetworkX call |
|---|---|---|
| Undirected components | BFS or DFS labeling | `nx.connected_components(G)` |
| Count only | `count` from labeling | `nx.number_connected_components(G)` |
| Component of one vertex | BFS from that vertex | `nx.node_connected_component(G, v)` |
| Strong components | Kosaraju or Tarjan | `nx.strongly_connected_components(D)` |
| Weak components | BFS ignoring direction | `nx.weakly_connected_components(D)` |
Common Follow-Up Operations
After finding components, you usually want to do something with them: keep the largest one, test whether the graph is connected, or collapse each strongly connected component into a single node.
import networkx as nx
G = nx.Graph([(0, 1), (1, 2), (3, 4)])
G.add_node(5)
largest = max(nx.connected_components(G), key=len)
print(sorted(largest)) # [0, 1, 2]
print(sorted(nx.node_connected_component(G, 4))) # [3, 4]
print(nx.is_connected(G)) # False
H = G.subgraph(largest).copy()
print(H.number_of_nodes(), H.number_of_edges()) # 3 2
D = nx.DiGraph([(0, 1), (1, 2), (2, 0), (2, 3)])
C = nx.condensation(D)
print(C.number_of_nodes(), C.number_of_edges()) # 2 1
print(nx.is_directed_acyclic_graph(C)) # True
print(C.graph["mapping"][0] == C.graph["mapping"][2]) # True
try:
list(nx.connected_components(D))
except nx.NetworkXNotImplemented as e:
print(type(e).__name__) # NetworkXNotImplementedG.subgraph(...) returns a read-only view that shares data with G. Call .copy() if you plan to modify the result or if the original graph might change. nx.condensation replaces each strongly connected component with a single node, and the result is always a directed acyclic graph. Its "mapping" attribute records which condensed node each original node belongs to.
Choosing the Right Call
Common Errors
- Missing isolated nodes. Building a graph only from an edge list drops vertices that have no edges. Add them with
G.add_nodes_from(range(n)). - Reusing a generator. A generator can be consumed only once. If you need to go through the components twice, call
list(...)on the result first. - Relying on component order. NetworkX does not document the order in which it yields components. Sort the components, or select by size, before you compare results.
- Performance at scale. NetworkX is written in pure Python. For graphs with tens of millions of edges, consider
scipy.sparse.csgraph.connected_componentsor igraph.
Exercise
Given D = nx.DiGraph([(0, 1), (1, 0), (1, 2), (3, 2)]), what do nx.numberstronglyconnectedcomponents(D) and nx.numberweaklyconnectedcomponents(D) return, and why?
Show answer
The strong count is 3: the components are {0, 1}, {2}, and {3}. Vertices 0 and 1 reach each other, but 2 cannot get back to 1, and 3 cannot be reached from 2. The weak count is 1, because once direction is ignored, every vertex is connected through vertex 2.
Exercise
Write one line that returns the number of nodes in the largest connected component of an undirected graph G.
Show answer
len(max(nx.connected_components(G), key=len))