Sub topic 14
Using NetworkX for Connected Components
The earlier chapters built every algorithm by hand: BFS and DFS labeling, union-find, flood fill, and Kosaraju's and Tarjan's algorithms for strongly connected components. In real projects you usually call a tested library instead. NetworkX is the standard pure-Python graph library. It includes functions for each kind of component covered in this tutorial.
This chapter assumes you are comfortable with Python sets, dictionaries, and generators, and that you know the definitions of connected, weakly connected, and strongly connected components from earlier chapters. You need NetworkX installed (pip install networkx). One optional section also uses SciPy.
Mapping the Hand-Written Algorithms to Library Calls
Every function you wrote earlier has a NetworkX counterpart. The table lists the ones you will use most.
| Task | Hand-written version | NetworkX function | Returns |
|---|---|---|---|
| All components, undirected | BFS or DFS labeling | `nx.connected_components(G)` | generator of sets |
| Count components, undirected | `count` from labeling | `nx.number_connected_components(G)` | int |
| Component containing one vertex | single BFS from that vertex | `nx.node_connected_component(G, v)` | set |
| Is the whole graph one piece? | `count == 1` | `nx.is_connected(G)` | bool |
| Strongly connected components | Kosaraju or Tarjan | `nx.strongly_connected_components(D)` | generator of sets |
| Weakly connected components | BFS ignoring direction | `nx.weakly_connected_components(D)` | generator of sets |
| Graph of SCCs (a DAG) | build it yourself after SCC | `nx.condensation(D)` | new `DiGraph` |
| Incremental merging | `DisjointSet` class | `nx.utils.UnionFind()` | union-find object |
Internally, connected_components runs a plain breadth-first search from each unvisited node, the same O(V + E) approach as the BFS chapter. strongly_connected_components uses an iterative version of Tarjan's algorithm, so deep graphs do not hit Python's recursion limit. NetworkX also provides kosaraju_strongly_connected_components if you want to compare results with your own implementation.
Undirected Components
The basic calls mirror the examples from earlier chapters.
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
print(sorted(nx.node_connected_component(G, 4)))
# [3, 4]
print(nx.is_connected(G))
# FalseNote the G.add_node(5) line. In the hand-written versions, you passed n and every index from 0 to n - 1 existed as a vertex. NetworkX only knows about nodes you add. A graph built only from an edge list has no isolated vertices, so your component count comes out too low.
Turning components into labels
The BFS chapter returned a label list that maps each vertex to its component index. NetworkX returns sets instead. A dictionary comprehension converts one form into the other:
import networkx as nx
G = nx.Graph([(0, 1), (1, 2), (3, 4)])
G.add_node(5)
label = {
node: idx
for idx, comp in enumerate(nx.connected_components(G))
for node in comp
}
print(dict(sorted(label.items())))
# {0: 0, 1: 0, 2: 0, 3: 1, 4: 1, 5: 2}With labels, checking whether two vertices are connected takes one dictionary lookup: label[u] == label[v]. That is much cheaper than running a new search for every query.
Nodes do not have to be integers
The hand-written code used list indices, so vertices had to be 0 to n - 1. NetworkX accepts any hashable value as a node: strings, tuples, or frozen objects. That removes the step of mapping names to integers.
import networkx as nx
G = nx.Graph([("alice", "bob"), ("bob", "carol"), ("dave", "erin")])
G.add_node("frank")
largest = max(nx.connected_components(G), key=len)
H = G.subgraph(largest).copy()
print(sorted(H.nodes()), H.number_of_edges())
# ['alice', 'bob', 'carol'] 2Here max(..., key=len) picks the largest component, a common first step when you clean up real-world networks. G.subgraph(nodes) returns a read-only view that stays linked to G. Calling .copy() turns it into an independent graph you can modify.
Directed Components
For a DiGraph, you have to choose which kind of connectivity you mean. NetworkX makes you say so explicitly.
import networkx as nx
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]]
print(nx.is_strongly_connected(D), nx.is_weakly_connected(D))
# False True
try:
nx.connected_components(D)
list(nx.connected_components(D))
except nx.NetworkXNotImplemented as e:
print("Error:", e)
# Error: not implemented for directed typeCalling connected_components on a directed graph raises NetworkXNotImplemented. This is intentional, because "connected" is ambiguous when edges have direction. If you really want to ignore direction, use weakly_connected_components, or convert with D.to_undirected().
The condensation graph
After you find the SCCs, you often want the DAG formed by collapsing each SCC to a single node. nx.condensation builds it. Each node in the result stores its original vertices in a members attribute. The graph-level mapping dictionary tells you which SCC each original vertex belongs to.
import networkx as nx
D = nx.DiGraph([(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 3)])
C = nx.condensation(D)
print(C.number_of_nodes(), C.number_of_edges())
# 2 1
order = list(nx.topological_sort(C))
print([sorted(C.nodes[i]["members"]) for i in order])
# [[0, 1, 2], [3, 4]]
print(C.graph["mapping"][4] == C.graph["mapping"][3])
# TrueThe condensation is always acyclic, so topological_sort works on it. That ordering answers questions like "which groups of modules must be built first" in a dependency graph, even when the original graph has cycles.
Incremental Connectivity with `UnionFind`
The traversal functions recompute everything from scratch. If edges arrive one at a time, as in the incremental connectivity chapter, recomputing after every edge costs O(V + E) per update. NetworkX includes a union-find structure with path compression and union by weight.
from networkx.utils import UnionFind
uf = UnionFind(range(6))
for u, v in [(0, 1), (1, 2), (3, 4)]:
uf.union(u, v)
print(uf[2] == uf[0]) # True
print(uf[5] == uf[3]) # False
print(sorted(sorted(s) for s in uf.to_sets()))
# [[0, 1, 2], [3, 4], [5]]Indexing uf[x] performs find and returns the representative. Unlike the DisjointSet class from earlier, this structure keeps no running component count. If you need the count after every edge, check whether uf[u] != uf[v] before calling union and decrement your own counter. Also pass all elements to the constructor. An element seen for the first time through uf[x] is added silently as a singleton, but to_sets() only reports elements the structure already knows about.
Gotchas
Generators are single-use
The component functions return generators. If you iterate once to count and a second time to process, the second loop gets nothing. Call list(...) when you need the components more than once.
Do not mutate the graph while iterating
The generator walks the graph lazily. If you remove nodes inside the loop, Python may raise RuntimeError: dictionary changed size during iteration, or you may get wrong results. Materialize the components first:
import networkx as nx
G = nx.Graph([(0, 1), (2, 3), (3, 4)])
G.add_node(5)
for comp in list(nx.connected_components(G)):
if len(comp) < 2:
G.remove_nodes_from(comp)
print(sorted(G.nodes()))
# [0, 1, 2, 3, 4]Empty graphs
nx.is_connected raises NetworkXPointlessConcept on a graph with no nodes, because connectivity is undefined there. number_connected_components returns 0 without complaint. Guard against empty input if your data can produce it.
Output order is not a contract
Components come out in an order that depends on node insertion order, and nodes within a set have no order. Sort the output in tests, as the examples here do, rather than relying on the order you happen to see.
When NetworkX Is Too Slow
NetworkX stores graphs as nested dictionaries and runs in pure Python. It handles graphs with up to a few million edges comfortably. Beyond that, memory use and constant factors start to hurt. For large integer-indexed graphs, SciPy's sparse-matrix routine does the same work in compiled code:
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
edges = np.array([(0, 1), (1, 2), (3, 4)])
n = 6
A = csr_matrix((np.ones(len(edges)), (edges[:, 0], edges[:, 1])), shape=(n, n))
count, labels = connected_components(A, directed=False)
print(count, labels.tolist())
# 3 [0, 0, 0, 1, 1, 2]
D = csr_matrix(([1, 1, 1, 1], ([0, 1, 2, 2], [1, 2, 0, 3])), shape=(4, 4))
print(connected_components(D, directed=True, connection="strong")[0])
# 2The output matches the BFS labeling from earlier in the tutorial: a count plus a label array. Because you pass shape=(n, n), isolated vertices like 5 are counted automatically. You give up NetworkX's flexible node types and rich API in exchange for speed. Libraries such as igraph and graph-tool make a similar trade.
Exercise
You load a social network with G = nx.Graph(edge_list) and get nx.number_connected_components(G) == 12. A colleague who used your hand-written BFS with n = 1000 users got 57. Neither program crashes. What explains the difference, and how do you fix the NetworkX version?
Show answer
The 45 extra components in the BFS result are users with no friendships. They appear as vertices because the BFS code creates every index from 0 to n - 1, but nx.Graph(edge_list) only creates nodes that appear in some edge. Fix it with G.add_nodes_from(range(1000)) (or the full user ID list) before counting. NetworkX will then report 57.
Exercise
Given D = nx.DiGraph([("a", "b"), ("b", "a"), ("b", "c"), ("c", "d"), ("d", "c")]), write code that prints the SCCs in an order where every SCC appears before any SCC it has edges into. What does it print?
Show answer
Use the condensation and a topological sort: C = nx.condensation(D) then print([sorted(C.nodes[i]["members"]) for i in nx.topological_sort(C)]). It prints [['a', 'b'], ['c', 'd']], because the only edge between SCCs runs from {a, b} to {c, d}.
Exercise
Why does list(nx.connected_components(D)) raise an error for a DiGraph D, and which two calls could you use instead, depending on intent?
Show answer
NetworkX refuses because "connected" is ambiguous for directed graphs and raises NetworkXNotImplemented. Use nx.strongly_connected_components(D) if every vertex in a component must reach every other vertex along edge directions. Use nx.weakly_connected_components(D) if direction should be ignored.