Sub topic 4
Writing DFS Recursively
This chapter turns the depth-first idea and the visited set from the previous chapters into working Python code. It assumes you can read Python functions and nested functions, use sets and dictionaries, and follow how the call stack grows and shrinks during recursion. Graphs are stored as adjacency-list dictionaries that map each vertex to a list of its neighbors.
Recursion fits DFS well because the call stack already does the bookkeeping that DFS needs. Each active call stands for one vertex on the current path. When a call returns, the search backtracks to the vertex that made the call.
The Complete Function
def dfs_recursive(graph, start):
visited = set()
order = []
def visit(node):
visited.add(node)
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visit(neighbor)
visit(start)
return order
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(dfs_recursive(graph, "A")) # ['A', 'B', 'D', 'C']The outer function dfs_recursive sets up state and starts the search. The inner function visit does the traversal. Because visit is a closure, it can read and change visited and order without passing them as arguments. Calling visited.add changes the set in place, so no nonlocal declaration is needed.
Anatomy of `visit`
Each line of visit has a specific job:
| Line | Role |
|---|---|
| `visited.add(node)` | Claims the vertex so no other call will enter it |
| `order.append(node)` | Records the vertex in the order it was discovered (pre-order) |
| `for neighbor in graph[node]` | Walks the vertex's outgoing edges in listed order |
| `if neighbor not in visited` | Skips vertices that are already claimed |
| `visit(neighbor)` | Goes one level deeper; this line is where the search goes deep |
The function has no explicit base case. The recursion stops on its own when every neighbor of a vertex is already visited, or when the vertex has no neighbors. Since each vertex can be entered only once, the total number of calls is at most the number of vertices.
Tracing the Calls
Follow the example graph step by step. visit("A") marks A and looks at B first. B is unvisited, so visit("B") runs, marks B, and moves on to D. visit("D") marks D, finds no neighbors, and returns. B has no more neighbors, so it returns too. Control comes back to A's loop, which moves on to C. visit("C") marks C, sees that D is already visited, skips it, and returns. Then A returns.
At its deepest point the call stack holds visit(A), visit(B), and visit(D). That stack is the path A → B → D, which is the path DFS is currently exploring.
Undirected Graphs
In an undirected adjacency list, each edge is stored twice, once in each direction. The same function works without changes. When visit("B") looks at its neighbor A, A is already in visited, so the search does not bounce back to its parent.
from collections import defaultdict
def dfs_recursive(graph, start):
visited = set()
order = []
def visit(node):
visited.add(node)
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visit(neighbor)
visit(start)
return order
edges = [("A", "B"), ("A", "C"), ("B", "C"), ("C", "D")]
undirected = defaultdict(list)
for u, v in edges:
undirected[u].append(v)
undirected[v].append(u)
print(dfs_recursive(undirected, "A")) # ['A', 'B', 'C', 'D']Returning Answers Through the Recursion
Many DFS problems need a result back from the search, not just a visit order. A reachability check returns True as soon as it finds the target, and each caller passes that True up without exploring any more neighbors.
def reachable(graph, source, target):
visited = set()
def visit(node):
if node == target:
return True
visited.add(node)
for neighbor in graph.get(node, ()):
if neighbor not in visited and visit(neighbor):
return True
return False
return visit(source)
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(reachable(graph, "A", "D")) # True
print(reachable(graph, "D", "A")) # FalseThe expression neighbor not in visited and visit(neighbor) uses short-circuit evaluation, so the recursive call runs only for unvisited neighbors. Using graph.get(node, ()) also handles vertices that appear only as edge targets and have no key in the dictionary. With plain graph[node], those vertices raise KeyError.
Common Errors
Marking visited too late
If you add the vertex to visited after the loop instead of before it, any cycle sends the search around forever. With {"a": ["b"], "b": ["a"]}, visit("a") calls visit("b"), which sees that a is not marked yet and calls visit("a") again. This repeats until Python raises RecursionError. Mark the vertex as the first thing you do when you enter it.
Mutable default arguments
A common shortcut is to put the visited set in the signature:
def dfs_bad(graph, node, visited=set()):
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs_bad(graph, neighbor, visited)
return visited
graph = {"A": ["B"], "B": []}
print(sorted(dfs_bad(graph, "A"))) # ['A', 'B']
other = {"X": ["Y"], "Y": []}
print(sorted(dfs_bad(other, "X"))) # ['A', 'B', 'X', 'Y']Python evaluates a default value once, when the function is defined. Every later call shares that same set, so the second search reports vertices from the first graph. Use visited=None and create the set inside the function, or use the closure pattern shown earlier.
Recursion depth
Each level of the search uses one Python stack frame, and CPython's default recursion limit is about 1000 frames. A long path, such as a linked chain of vertices or a large grid, goes past that limit:
import sys
def dfs_recursive(graph, start):
visited = set()
order = []
def visit(node):
visited.add(node)
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visit(neighbor)
visit(start)
return order
print(sys.getrecursionlimit()) # typically 1000
chain = {i: [i + 1] for i in range(5000)}
chain[5000] = []
try:
dfs_recursive(chain, 0)
except RecursionError:
print("RecursionError: path too deep")You can raise the limit with sys.setrecursionlimit, but the operating system's thread stack can still overflow and crash the interpreter. The reliable fix is an explicit stack, which the next chapter covers.
Neighbor Order Determines Visit Order
Recursive DFS explores neighbors in the order they appear in each adjacency list. If you change "A": ["B", "C"] to "A": ["C", "B"], the result becomes ['A', 'C', 'D', 'B']. Both orders are valid DFS orders. Tests that compare exact output should fix the order of each adjacency list, for example by sorting it.
Exercise
For graph = {"1": ["2", "3"], "2": ["4"], "3": ["4", "5"], "4": [], "5": ["1"]}, what does dfs_recursive(graph, "1") return, and what is the deepest the call stack gets?
Show answer
['1', '2', '4', '3', '5']. The deepest stack is three visit calls: either 1 → 2 → 4 or 1 → 3 → 5. When visit("5") runs, its neighbor "1" is already visited, so the search does not go deeper.
Exercise
Change dfs_recursive so it returns a dictionary that maps each reached vertex to the vertex it was discovered from, with the start vertex mapped to None.
Show answer
Replace visited with parent = {start: None}. Inside visit, loop over the neighbors and, for each neighbor not in parent, set parent[neighbor] = node and then call visit(neighbor). Return parent. A vertex counts as visited once it is a key in parent, so the dictionary also replaces the visited set.
Exercise
A teammate moves visited.add(node) to just after the for loop in visit. On which inputs does the function still return the right result, and what goes wrong on the others?
Show answer
It still works on graphs where no vertex can be reached twice, such as trees with edges pointing away from the root. If two paths lead to the same vertex, as in the A/B/C/D example, that vertex is visited and recorded twice. Any cycle, including every undirected edge, causes unbounded recursion that ends in RecursionError.