Sub topic 3
Remembering Where You Have Been
This chapter assumes you can read Python, know how sets and dictionaries work, and are comfortable with recursion. It uses the adjacency-list dictionaries from the earlier chapters.
Why DFS Needs a Memory
Depth-first search follows edges as far as it can. In a tree that is safe, because every path eventually ends. Most graphs contain cycles, though, and an undirected graph lists every edge twice: once from each end. If DFS cannot recall which vertices it has already reached, it follows the same edges again and again and never stops.
The fix is a visited set. A visited set holds every vertex the search has discovered so far. Before DFS moves to a neighbor, it checks the set. If the neighbor is already in it, DFS skips that neighbor.
Seeing the Problem
The function below explores a graph with an optional visited set. A step limit stops the run without a visited set, which would otherwise never end.
def explore(graph, node, visited, order, limit):
if len(order) >= limit:
return
if visited is not None:
if node in visited:
return
visited.add(node)
order.append(node)
for neighbor in graph[node]:
explore(graph, neighbor, visited, order, limit)
triangle = {"A": ["B", "C"], "B": ["A", "C"], "C": ["A", "B"]}
no_memory = []
explore(triangle, "A", None, no_memory, limit=8)
print(no_memory) # ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B']
with_memory = []
explore(triangle, "A", set(), with_memory, limit=8)
print(with_memory) # ['A', 'B', 'C']Without memory, the search bounces between A and B over the edge they share and never reaches C. With memory, each vertex is processed exactly once.
Choosing the Right Structure
Use a set or a dictionary for visited tracking. A membership test on either takes O(1) time on average. A list takes O(n) per test, which turns a linear traversal into a quadratic one on large graphs. Set elements must be hashable, so use tuples such as (row, col) for vertices that are coordinates, not lists.
If vertices are numbered 0 to n - 1, a list of booleans visited = [False] * n works just as well and uses less memory.
When to Mark a Vertex
Mark a vertex as visited when you first discover it, before you explore its neighbors. If you mark it only after its neighbors are done, a cycle leads the search back to the vertex while it is still unmarked, and the search loops again.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| No visited set | Infinite recursion or `RecursionError` | Check membership before every move |
| Marking after exploring neighbors | Revisits along cycles | Mark on discovery |
| Using a list for visited | Slow on large graphs | Use a set or boolean array |
| Creating a new set per call | Memory never shared, search still loops | Pass one set through every call |
| Unhashable vertices | `TypeError: unhashable type` | Convert to tuples |
Exercise
A student writes def explore(graph, node, visited=set()) and calls explore(g, "A") twice in the same program. The second call returns almost nothing. Why?
Show answer
Python evaluates a default argument once, when the function is defined, so both calls share the same set. After the first call, every reachable vertex is already in it. Use visited=None and create a new set inside the function when it is None.
Exercise
In an undirected graph with 4 vertices and 5 edges, how many neighbor entries does DFS check against the visited set if it starts from one vertex and reaches all of them?
Show answer
10. Each undirected edge appears in two adjacency lists, so the search checks 2 × 5 = 10 entries. Only 3 of those checks lead to a new vertex.