Sub topic 1
Representing Graphs for Traversal
Depth-first search (DFS) repeatedly asks one question: "Which vertices can I reach from here?" The way you store a graph decides how quickly that question gets answered. This chapter sets up the representation used in the rest of the tutorial.
Prerequisites
This chapter assumes you can already:
- Write basic Python, including functions and loops.
- Use lists, sets, and dictionaries.
- Use basic graph terms: vertex, edge, directed, undirected.
- Read Big-O notation.
The Adjacency List
An adjacency list maps each vertex to the list of its neighbors. In Python, a dictionary of lists fits this well:
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(graph["A"]) # ['B', 'C']This is a directed graph. Each key is a vertex, and each value lists the vertices that its outgoing edges point to.
Two properties make this the standard choice for DFS:
- Finding a vertex's neighbors costs time proportional to how many neighbors it has. You never scan vertices that are not connected to it.
- Total storage is O(V + E): one entry per vertex plus one list item per edge, or two per edge in an undirected graph.
Building One from an Edge List
Graphs often arrive as a list of pairs. This helper turns those pairs into an adjacency list:
def build_graph(edges, directed=False):
graph = {}
for u, v in edges:
graph.setdefault(u, []).append(v)
graph.setdefault(v, []) # make sure v is a key even with no out-edges
if not directed:
graph[v].append(u)
return graph
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")]
print(build_graph(edges, directed=True))
# {'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': []}
print(build_graph(edges))
# {'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'D'], 'D': ['B', 'C']}In an undirected graph, each edge appears in both endpoints' lists. That is why the undirected version stores 2E list items.
Adjacency List vs. Adjacency Matrix
| Representation | Storage | List neighbors of v | Check if edge (u, v) exists |
|---|---|---|---|
| Adjacency list | O(V + E) | O(deg(v)) | O(deg(u)) |
| Adjacency matrix | O(V²) | O(V) | O(1) |
A matrix makes DFS cost O(V²), because each vertex has to scan a full row. That is wasteful for sparse graphs, where E is much smaller than V². Use a matrix only when the graph is dense or when you need constant-time edge lookups.
Common Errors
- Forgetting the reverse edge. In an undirected graph, adding only
u → vsilently turns it into a directed graph. DFS will then miss vertices. - Losing isolated vertices. An edge list cannot express a vertex with no edges at all. Add such vertices explicitly, for example
graph.setdefault(x, []). - Assuming neighbor order does not matter. DFS visits neighbors in list order. Different orders give different but equally valid traversals. Fix the order if you need reproducible output.
Exercise
You call build_graph([("x", "y"), ("y", "z")]) with the default directed=False. What dictionary is returned, and how many list items does it hold in total?
Show answer
{'x': ['y'], 'y': ['x', 'z'], 'z': ['y']}. It holds 4 list items, which is 2E for E = 2 undirected edges.
Exercise
A graph has 100,000 vertices and 300,000 edges. Why is an adjacency matrix a poor choice for running DFS on it?
Show answer
The matrix needs 10^10 cells, and DFS would scan a full row per vertex, which is O(V²) work. An adjacency list uses O(V + E), about 400,000 entries, and DFS runs in O(V + E).