Sub topic 14
Depth-first search with an explicit stack
This chapter assumes you know how a stack works (push, pop, peek), can read a graph stored as an adjacency list (a dictionary mapping each node to a list of neighbors), and understand why recursion uses the call stack.
Recursion and the stack are the same idea
Depth-first search (DFS) explores a graph by following one path as far as it goes. When it hits a dead end, it backs up to the most recent node that still has unexplored neighbors. "Most recent first" is last in, first out.
A recursive DFS gets this behavior from the call stack. Each call holds one node, and returning from a call backs up one step. An explicit stack does the same job with a list you control. The reason to switch is that deep recursion can overflow the call stack. Python, for example, stops at about 1,000 nested calls by default. A list on the heap has no such limit.
The algorithm
def dfs(graph, start):
visited = set()
order = []
stack = [start]
while stack:
node = stack.pop()
if node in visited:
continue
visited.add(node)
order.append(node)
for neighbor in reversed(graph[node]):
if neighbor not in visited:
stack.append(neighbor)
return order
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(dfs(graph, "A")) # ['A', 'B', 'D', 'C']Walk through it:
- The stack starts as
[A]. PopA, visit it, and push its neighbors in reverse: the stack is[C, B]. - Pop
B, visit it, pushD: the stack is[C, D]. - Pop
D, visit it. It has no neighbors: the stack is[C]. - Pop
C, visit it, and skipDbecause it is already visited. The stack is empty and the search ends.
Details that cause bugs
Mark nodes when you pop them, not when you push them. A node can be pushed more than once, because D is a neighbor of both B and C. The if node in visited: continue check discards the extra copies. Marking at push time gives a different visit order, and it can differ from what recursive DFS produces.
Reverse the neighbors. A stack pops the last item pushed. Without reversed, the search would visit C before B. Reversing makes the order match the listed order, and so match a recursive version.
Visited tracking is required for graphs with cycles. Without it, the loop never ends on a cycle such as A -> B -> A. Trees have no cycles, so a tree traversal can skip the set.
Cost
Each node is visited once, and each edge is examined once when its source node is visited. Time is O(V + E), where V is the number of nodes and E is the number of edges. The stack can hold duplicates, so its worst-case size is O(E), plus O(V) for the visited set.
| Version | Depth limit | Extra memory |
|---|---|---|
| Recursive | Call stack size (about 1,000 in Python) | One frame per level of depth |
| Explicit stack | Available heap memory | Stack list, up to O(E) entries |
Exercise
In the dfs function, what would change if you removed the reversed(...) call, and does the function still visit every reachable node?
Show answer
It would still visit every reachable node, because the stack and visited set are unchanged. The order would change: for the example graph the result would be ['A', 'C', 'D', 'B'], since C is pushed last and popped first.
Exercise
Why does the function check if node in visited after popping, even though it already checks neighbor not in visited before pushing?
Show answer
A node can be pushed several times before it is first popped, as D is in the example. The check at pop time discards the later copies so each node is processed once.