Sub topic 1
Representing Graphs for Traversal
Depth-first search (DFS) can only be as fast and as correct as the graph structure you give it. Before writing any traversal, you need a representation that answers one question cheaply: "Given this vertex, what are its neighbors?" This chapter covers the main representations, shows why the adjacency list is the default for DFS, and lists the representation mistakes that cause traversal bugs later.
Prerequisites
This chapter assumes you are comfortable with:
- Basic Python: functions, loops, and tuples
- Lists, sets, and dictionaries, including how dictionary keys work
- Graph terms: a vertex is a node, an edge connects two vertices, and edges can be directed (one-way) or undirected (two-way)
- Big-O notation for describing time and memory cost
Recursion is not needed yet. It becomes central in later chapters.
The Question a Traversal Keeps Asking
Every step of DFS stands at some vertex and asks for its neighbors. A graph with V vertices and E edges might be explored by calling "get neighbors" once per vertex, so the cost of that call decides the cost of the whole traversal. A good representation for DFS:
- Returns the neighbors of a vertex in time proportional to how many there are.
- Uses memory proportional to the size of the graph.
- Gives a predictable neighbor order, so the traversal output is repeatable.
Three Common Representations
Edge list
An edge list is a plain list of pairs, such as [("A", "B"), ("A", "C")]. Graph data usually arrives in this form, from files, databases, or APIs. It is compact, but finding the neighbors of one vertex means scanning every edge, which costs O(E) per lookup. You will usually convert an edge list into something else before traversing.
Adjacency matrix
An adjacency matrix is a V × V grid in which entry [i][j] is 1 if there is an edge from vertex i to vertex j. Checking whether a specific edge exists takes O(1). Listing the neighbors of a vertex still means scanning a whole row, which costs O(V) even when the vertex has only one neighbor. The matrix also needs O(V²) memory no matter how few edges exist.
Adjacency list
An adjacency list maps each vertex to a list of its neighbors. In Python this is a dictionary of lists. Listing the neighbors of u costs time proportional to the degree of u, which is its number of outgoing edges. Total memory is O(V + E). This is the representation that every code example in this tutorial uses.
| Representation | Memory | List neighbors of u | Check edge (u, v) | Good fit |
|---|---|---|---|---|
| Edge list | O(E) | O(E) | O(E) | Input format, edge-centric algorithms |
| Adjacency matrix | O(V²) | O(V) | O(1) | Dense graphs, frequent edge lookups |
| Adjacency list | O(V + E) | O(degree(u)) | O(degree(u)) | Traversals such as DFS and BFS |
The Running Example
The next few chapters reuse this small directed graph:
As an adjacency list it looks like this:
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}Note that "D" appears as a key with an empty list. D has no outgoing edges, but it is still a vertex, and the traversal code will look it up.
Building an Adjacency List from an Edge List
Building the list by hand works for small examples. Real code converts an edge list. The function below handles directed and undirected graphs, and it guarantees that every vertex appears as a key.
def build_graph(edges, directed=False, vertices=()):
graph = {v: [] for v in vertices} # include isolated vertices
for u, v in edges:
graph.setdefault(u, []).append(v)
graph.setdefault(v, []) # make sure sinks exist as keys
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, directed=False))
# {'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'D'], 'D': ['B', 'C']}
print(build_graph([("A", "B")], directed=True, vertices=["Z"]))
# {'Z': [], 'A': ['B'], 'B': []}Three details matter here:
- Undirected edges are stored twice, once in each direction. An undirected graph with E edges therefore has 2E list entries, which is still O(E).
- Sinks get keys. A sink is a vertex with no outgoing edges. Without the second
setdefault,graph["D"]would raise aKeyError. - Isolated vertices need explicit input. A vertex with no edges at all never appears in an edge list. The
verticesparameter lets you include it. This matters when you count components or traverse the whole graph.
Neighbor Order Shapes the Traversal
DFS visits neighbors in the order the list stores them. With "A": ["B", "C"], DFS goes to B first. With "A": ["C", "B"], it goes to C first. Both orders are valid DFS runs, but they produce different visit orders, different trees, and different topological orderings.
This is why the tutorial uses lists for neighbors and not sets. Iteration order over a Python set of strings can change between runs, because string hashing is randomized per process. If your tests compare exact output, use lists. If you need fast "is v a neighbor of u?" checks as well, keep a separate set next to the list.
Implicit Graphs
Sometimes you never build an adjacency list at all. In a grid, a maze, or a puzzle state space, you can compute neighbors on demand. The graph exists only as a function. Here, each land cell "1" in a grid is a vertex, and its neighbors are the adjacent land cells above, below, left, and right:
def grid_neighbors(grid, r, c):
rows, cols = len(grid), len(grid[0])
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1":
yield nr, nc
grid = ["11000", "11000", "00100", "00011"]
print(list(grid_neighbors(grid, 0, 0))) # [(1, 0), (0, 1)]
print(list(grid_neighbors(grid, 2, 2))) # []This uses O(1) extra memory for the graph itself, which is useful when the graph is huge or infinite. The grid chapter builds flood fill on this idea.
Weighted Graphs
DFS ignores edge weights, but your data may still carry them. Store (neighbor, weight) pairs, or a dictionary per vertex, and unpack only the neighbor during traversal:
weighted = {"A": [("B", 4), ("C", 1)], "B": [("D", 2)], "C": [("D", 7)], "D": []}
for neighbor, _weight in weighted["A"]:
print(neighbor)
# B
# CValidating a Graph Before Traversal
Malformed input causes most "DFS crashed" bugs. A quick check finds neighbors that have no key of their own:
def missing_vertices(graph):
return {v for nbrs in graph.values() for v in nbrs if v not in graph}
print(missing_vertices({"A": ["B", "C"], "B": []})) # {'C'}
print(missing_vertices({"A": ["B"], "B": []})) # set()Common Representation Errors
- Forgetting sinks or isolated vertices. The result is a
KeyError, or vertices that are never counted. - Storing an undirected edge in one direction only. DFS from one endpoint then cannot reach the other, and component counts come out too high.
- Duplicate edges. If an edge list repeats
("A", "B"), B appears twice in A's list. DFS stays correct because it tracks visited vertices, but you do extra work, and degree counts are wrong. Deduplicate if your input can contain repeats. - Self-loops. An edge
("A", "A")is legal. Remember that it exists, because later chapters treat it as a cycle in directed graphs. - Choosing a matrix for a sparse graph. Traversal becomes O(V²) when it could have been O(V + E).
Exercise
You are given the undirected edge list [(1, 2), (2, 3), (4, 5)] and told the graph has vertices 1 through 6. Write the adjacency list that build_graph(edges, directed=False, vertices=range(1, 7)) returns, and say what would go wrong for a component-counting algorithm if you left out the vertices argument.
Show answer
The result is {1: [2], 2: [1, 3], 3: [2], 4: [5], 5: [4], 6: []}. Without the vertices argument, vertex 6 never appears because it has no edges. A component counter would report 2 components instead of the correct 3, because the isolated vertex 6 is its own component.
Exercise
A graph has 10,000 vertices and 30,000 directed edges. Roughly how many cells does an adjacency matrix need, how many list entries does an adjacency list need, and which should you use for DFS?
Show answer
The matrix needs 10,000 × 10,000 = 100,000,000 cells. The adjacency list needs 10,000 keys plus 30,000 neighbor entries, about 40,000 items in total. Use the adjacency list. DFS on it runs in O(V + E), about 40,000 steps, while the matrix forces an O(V) row scan per vertex, about 100,000,000 steps.
Exercise
Why might two runs of the same DFS program print different visit orders if the graph is stored as {"A": {"B", "C"}, ...} with sets of strings, and how do you fix it?
Show answer
Python randomizes string hashing per process, so the iteration order of a set of strings can change between runs. DFS visits neighbors in iteration order, so the visit order changes too. Store neighbors in lists, or sort them before iterating, to get repeatable output.