Sub topic 1
Representing a Graph as an Adjacency List
Prerequisites
This chapter assumes you know basic Python (lists, loops, functions), how stacks and queues work, basic graph terms (vertex, edge, undirected), and Big-O notation.
Building the Adjacency List
An adjacency list stores, for each vertex, the list of its neighbors. If vertices are numbered 0 to n - 1, a list of lists works well. In an undirected graph, every edge (u, v) must be added in both directions. Forgetting the reverse direction is the most common bug here, and it splits components that should be joined.
For the edges (0, 1), (1, 2), (3, 4) with 6 vertices, adj becomes [[1], [0, 2], [1], [4], [3], []]. Vertex 5 has no edges, but it still gets an empty list.
What a Connected Component Is
A connected component is a largest set of vertices in which every pair is joined by a path. Every vertex belongs to exactly one component. An isolated vertex is a component by itself.
Labeling Components with Breadth-First Search
To label the components, loop over every vertex. When you reach one that has no label yet, start a breadth-first search (BFS) from it, and give every vertex that BFS reaches the current component number.
from collections import deque
def connected_components(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
label = [-1] * n
count = 0
for start in range(n):
if label[start] != -1:
continue
label[start] = count
queue = deque([start])
while queue:
u = queue.popleft()
for v in adj[u]:
if label[v] == -1:
label[v] = count
queue.append(v)
count += 1
return count, label
print(connected_components(6, [(0, 1), (1, 2), (3, 4)]))
# (3, [0, 0, 0, 1, 1, 2])Label each vertex when you add it to the queue, not when you remove it. If you wait until removal, the same vertex can be queued more than once.
Labeling Components with Iterative Depth-First Search
Depth-first search (DFS) gives the same components. Recursive DFS can go past Python's default recursion limit of about 1000 on large components, so this version uses an explicit stack.
def components_dfs(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
seen = [False] * n
result = []
for start in range(n):
if seen[start]:
continue
seen[start] = True
stack = [start]
component = []
while stack:
u = stack.pop()
component.append(u)
for v in adj[u]:
if not seen[v]:
seen[v] = True
stack.append(v)
result.append(sorted(component))
return result
print(components_dfs(6, [(0, 1), (1, 2), (3, 4)]))
# [[0, 1, 2], [3, 4], [5]]Exercise
If you build the adjacency list with only adj[u].append(v) and then run the BFS above on edges [(1, 0), (2, 1)] with n = 3, how many components does it report?
Show answer
It reports 3. With one-directional entries, adj is [[], [0], [1]]. BFS from 0 reaches nothing. Vertex 1 is still unlabeled when the loop reaches it, so it starts a new component, even though its neighbor 0 is already labeled. Vertex 2 does the same. The correct answer is 1.