Sub topic 3
Remembering Where You Have Been
This chapter assumes you can read Python functions that use sets and dictionaries. It also assumes you understand recursion and the call stack, and that you know the adjacency-list representation from the first chapter. The aim is narrow: to explain why DFS must remember which vertices it has already reached, how to store that memory, and when to update it.
Why a Traversal Needs Memory
A graph is not a tree. Two different paths can lead to the same vertex, and a path can loop back to where it started. If you explore every edge without checking anything, you run into two separate problems.
- Cycles cause infinite work. In the graph
a → b → a, an unchecked exploration goes fromatob, back toa, and keeps going until the call stack overflows. - Shared descendants cause repeated work. Even in a graph with no cycles, a vertex reachable along many paths gets explored once for each path. The number of paths can grow exponentially with the size of the graph.
The fix for both is a visited set, a record of every vertex the search has already discovered. Before you move to a neighbor, you check whether it is in the set. If it is, you skip it.
Seeing the Cost
The code below builds a chain of "diamonds". Each diamond splits into two branches that meet again at the next vertex. It counts how many times the exploration function runs with and without a visited set, and then runs the unchecked version on a two-vertex cycle.
def build_diamond_chain(k):
graph = {}
for i in range(k):
top, left, right, bottom = f"n{i}", f"l{i}", f"r{i}", f"n{i + 1}"
graph[top] = [left, right]
graph[left] = [bottom]
graph[right] = [bottom]
graph[f"n{k}"] = []
return graph
def count_calls_naive(graph, start):
calls = 0
def explore(node):
nonlocal calls
calls += 1
for neighbor in graph[node]:
explore(neighbor)
explore(start)
return calls
def count_calls_visited(graph, start):
visited = set()
calls = 0
def explore(node):
nonlocal calls
calls += 1
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
explore(neighbor)
explore(start)
return calls
g = build_diamond_chain(10)
print(len(g)) # 31 vertices
print(count_calls_naive(g, "n0")) # 4093
print(count_calls_visited(g, "n0")) # 31
cycle = {"a": ["b"], "b": ["a"]}
try:
count_calls_naive(cycle, "a")
except RecursionError:
print("RecursionError: the search never stopped")The graph has 31 vertices, and the unchecked version makes 4,093 calls. Vertex n{i} is reached once for each of the 2^i paths that lead to it. If you add ten more diamonds, the naive count goes past four million while the visited version makes 61 calls. With the visited set, each vertex is explored exactly once, and that guarantee is what the O(V + E) bound in a later chapter depends on.
The Decision at Each Edge
Each time DFS looks at an edge from the current vertex to a neighbor, it makes the same small decision.
In an undirected graph, the adjacency list stores every edge twice: u lists v, and v lists u. When DFS goes from u to v, one of v's neighbors is u. The visited check is what stops the search from bouncing straight back. You do not need separate parent-tracking logic just to traverse an undirected graph.
Choosing a Representation
The visited structure has to support two operations: "add this vertex" and "have I seen this vertex?" Both should take constant time.
| Representation | Use when | Membership cost | Notes |
|---|---|---|---|
| `set()` | Vertex labels are hashable (strings, ints, tuples) | O(1) average | The default choice for dictionary-based graphs |
| `[False] * n` | Vertices are integers `0..n-1` | O(1) | Less memory overhead and faster in tight loops |
| `dict` of vertex to data | You also need a parent, depth, or time for each vertex | O(1) average | The keys serve as the visited set |
| `list` of seen vertices | Never | O(V) | Turns the whole search into O(V²) or worse |
A dictionary is useful because it records how each vertex was reached. If you store each vertex's parent, the keys tell you what has been visited and the values let you rebuild a path.
def dfs_parents(graph, start):
parent = {start: None}
def visit(node):
for neighbor in graph[node]:
if neighbor not in parent:
parent[neighbor] = node
visit(neighbor)
visit(start)
return parent
def path_to(parent, target):
if target not in parent:
return None
path = []
while target is not None:
path.append(target)
target = parent[target]
return path[::-1]
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
parents = dfs_parents(graph, "A")
print(parents) # {'A': None, 'B': 'A', 'D': 'B', 'C': 'A'}
print(path_to(parents, "D")) # ['A', 'B', 'D']
print(path_to(parents, "Z")) # NoneThe path DFS finds is a valid path, but it is not necessarily the shortest one. The last chapter explains why breadth-first search is the right tool when you need shortest paths.
When to Mark a Vertex
The rule for recursive DFS is to mark a vertex as soon as you discover it, before you explore its neighbors. If you mark it only after its neighbor loop finishes, a cycle leads back to the vertex while it is still unmarked, and the recursion never ends.
Iterative DFS with an explicit stack has a second option. You can mark a vertex when you push it or when you pop it. The two choices produce different visit orders, and the next chapter covers that trade-off. Whichever you choose, a vertex must never be processed twice.
Common Errors
Visited State That Leaks Between Calls
Python evaluates a default argument once, when the function is defined. A mutable default therefore carries over from one call to the next.
def reachable_buggy(graph, start, visited=set()):
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
reachable_buggy(graph, neighbor, visited)
return visited
def reachable(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
reachable(graph, neighbor, visited)
return visited
g = {"A": ["B"], "B": [], "X": ["Y"], "Y": []}
print(sorted(reachable_buggy(g, "A"))) # ['A', 'B']
print(sorted(reachable_buggy(g, "X"))) # ['A', 'B', 'X', 'Y'] (wrong)
print(sorted(reachable(g, "A"))) # ['A', 'B']
print(sorted(reachable(g, "X"))) # ['X', 'Y']Other Mistakes to Recognize
- Creating the set inside the recursive function. Each call then gets a fresh, empty set, and nothing is remembered. Create the set once, outside the recursion, and share it.
- Unhashable vertex labels. Grid coordinates stored as lists such as
[r, c]cannot go into a set. Use tuples such as(r, c). - Removing vertices from visited on return. "Un-marking" a vertex makes sense when you enumerate every simple path, which the backtracking chapter covers. In a plain traversal it brings back the exponential blow-up shown earlier.
- Resetting visited between start vertices. When you loop over all vertices to cover a disconnected graph, keep a single visited set for the whole loop. Otherwise the search re-explores regions it has already covered.
Exercise
A student writes recursive DFS that calls visited.add(node) on the line after the for-loop over neighbors, instead of before it. On the graph {"a": ["b"], "b": ["c"], "c": []} the output looks correct. What happens on {"a": ["b"], "b": ["a"]}, and why?
Show answer
It recurses forever and raises RecursionError. When visit("a") runs, "a" is not marked yet, so its neighbor "b" passes the check. Then "b" finds that "a" is still unmarked and calls visit("a") again. Neither vertex is ever marked, because both calls are stuck inside their loops. The first graph has no cycle, so the bug never shows up there.
Exercise
Your graph has vertices labeled 0 to 999,999 and stores them in a list of adjacency lists. Which visited representation would you pick, and what goes wrong if you use a Python list that you append vertices to and check with "in"?
Show answer
Use a boolean array, visited = [False] * n, which gives O(1) checks with low memory overhead. A set would also be correct. If you append to a list and test with "in", every membership check scans the list in O(V) time, so the traversal degrades to roughly O(V · (V + E)), which is far too slow for a million vertices.
Exercise
Modify dfs_parents so that it also records each vertex's depth (the number of tree edges from start) and returns both dictionaries. What is the depth of "D" in the example graph, and is it the shortest distance from "A"?
Show answer
Initialize depth = {start: 0}, and when you discover a neighbor, set depth[neighbor] = depth[node] + 1 next to parent[neighbor] = node. In the example, "D" is discovered through "B" with depth 2. That is also the shortest distance here, but only by coincidence. DFS depth is the length of the path DFS happened to take, which in general can be longer than the shortest path.