Sub topic 2
Go Deep, Then Backtrack: The Core Idea
This chapter assumes you can read basic Python, know what a dictionary and a list are, understand how recursive calls stack up, and know the difference between a vertex and an edge. It also assumes the adjacency-list representation from the previous chapter, where each vertex maps to a list of its neighbors.
The goal here is to build a working mental model of depth-first search (DFS) before getting into implementation details. Once the strategy is clear, the code in later chapters reads as a direct translation of it.
The Strategy in One Sentence
Depth-first search always continues from the most recently reached vertex that still has an unexplored edge. In practice this means you pick an edge and follow it. From the new vertex you pick another edge and follow that one too. You keep going until you reach a vertex with nowhere new to go. At that point you step back to the previous vertex and try its next edge. That step back is called backtracking.
Exploring a maze with one hand on the wall works the same way. You walk down a corridor until you hit a dead end, then retrace your steps only as far as the last junction with an untried branch. You never jump across the maze to some distant junction. You always resume from the closest one behind you.
A Worked Trace
Here is a small directed graph. Neighbor lists are explored in the order written, so A tries B before C.
The table below traces DFS starting at A. The "current path" column lists the vertices between the start and the vertex being worked on right now.
| Step | Action | Current path |
|---|---|---|
| 1 | Start at A | A |
| 2 | Follow A → B | A, B |
| 3 | Follow B → D | A, B, D |
| 4 | D has no edges; backtrack to B | A, B |
| 5 | Follow B → E | A, B, E |
| 6 | E has no edges; backtrack to B | A, B |
| 7 | B is exhausted; backtrack to A | A |
| 8 | Follow A → C | A, C |
| 9 | Follow C → F | A, C, F |
| 10 | F has no edges; backtrack to C | A, C |
| 11 | C is exhausted; backtrack to A | A |
| 12 | A is exhausted; search ends | (empty) |
The vertices are first reached in the order A, B, D, E, C, F. Notice that DFS fully finishes everything under B before it ever touches C. That is what "depth-first" means: it finishes one branch completely before starting a sibling branch.
The Path Behaves Like a Stack
Look at the "current path" column again. Vertices are only ever added to the right end, and only ever removed from the right end. That is exactly how a stack behaves, a last-in, first-out collection. Going deeper is a push. Backtracking is a pop.
This observation is the central fact behind every DFS implementation:
- In a recursive version, the program's call stack holds the path. Each recursive call pushes a vertex, and returning from the call pops it.
- In an iterative version, you keep an explicit stack data structure yourself.
Both are covered in their own chapters. For now, remember that whichever form you use, there is a stack, and its top is the vertex DFS is working on right now.
Seeing It Run
The graph above happens to be a tree. A tree has exactly one route from the root to each vertex, so no vertex can be reached twice. That makes it possible to watch the go-deep-then-backtrack pattern without any extra bookkeeping. The program below prints enter when DFS arrives at a vertex and leave when it backtracks out of it. Indentation shows the current depth.
tree = {
"A": ["B", "C"],
"B": ["D", "E"],
"C": ["F"],
"D": [],
"E": [],
"F": [],
}
def explore(node, depth=0):
print(" " * depth + f"enter {node}")
for child in tree[node]:
explore(child, depth + 1)
print(" " * depth + f"leave {node}")
explore("A")Output:
enter A
enter B
enter D
leave D
enter E
leave E
leave B
enter C
enter F
leave F
leave C
leave AEach enter/leave pair encloses everything explored beneath that vertex, and the pairs nest like parentheses. The pair for B contains the pairs for D and E, and closes before the pair for C opens. This nesting comes back later in the tutorial. Discovery and finish times are timestamps on these enter and leave events, and many DFS applications depend on the fact that the intervals nest this way.
Neighbor Order Changes the Result
DFS is not a single fixed ordering of vertices. It is a strategy, and the visiting order it produces depends on which edge you try first at each vertex. If you reverse every neighbor list in the example, the trace becomes A, C, F, B, E, D.
tree = {"A": ["B", "C"], "B": ["D", "E"], "C": ["F"], "D": [], "E": [], "F": []}
def preorder(node, reverse=False):
children = reversed(tree[node]) if reverse else tree[node]
result = [node]
for child in children:
result.extend(preorder(child, reverse))
return result
print(preorder("A")) # ['A', 'B', 'D', 'E', 'C', 'F']
print(preorder("A", reverse=True)) # ['A', 'C', 'F', 'B', 'E', 'D']Both outputs are valid depth-first orders. This has practical consequences:
- If a test compares a DFS order to an exact expected list, the test is also fixing the neighbor order. If you build the adjacency lists from a set, or from a dictionary filled in a different order, you can get a different correct answer.
- An iterative version that pushes neighbors onto a stack in listed order explores them in reverse order, because the last neighbor pushed is the first one popped. The iterative chapter shows how to correct for this.
- Properties that DFS-based algorithms rely on, such as "a cycle exists" or "this ordering respects all edges", hold no matter which neighbor order you use. The specific sequence of vertices does not stay the same.
Edge Cases Worth Noticing Now
Several situations show up in every later chapter. It helps to see them in terms of the core idea first.
| Situation | What the strategy does | Covered in |
|---|---|---|
| Start vertex has no edges | Pushes the start, finds nothing, pops it, ends | This chapter |
| A vertex is reachable by two routes | Reaches it twice unless something remembers it | Remembering Where You Have Been |
| The graph has a cycle | Loops forever unless something remembers visited vertices | Remembering Where You Have Been; Detecting Cycles |
| Undirected edge back to the vertex you just came from | Immediately goes back, since every undirected edge works in both directions | Remembering Where You Have Been |
| Some vertices are unreachable from the start | Never reaches them; one search covers only what the start can reach | Visiting Every Vertex: The DFS Forest |
| A very long path, such as a 100,000-vertex chain | Stack depth grows with path length, which can overflow Python's recursion limit | Replacing Recursion with an Explicit Stack |
The last row matters in practice. The memory DFS needs grows with the length of the current path. On a bushy, shallow graph that is small. On a long chain it equals the number of vertices.
Why This Strategy Is Useful
Going deep first has some properties that the rest of the tutorial uses:
- The current path is always a real path from the start to the current vertex. This makes DFS a natural fit for finding a route, and for backtracking searches that build a candidate solution one choice at a time.
- When DFS leaves a vertex, everything reachable below it has been explored. This "finished" moment is the basis of topological sorting.
- If an edge leads back to a vertex that is still on the current path, the graph has a cycle. Cycle detection is built on this fact.
Breadth-first search reaches vertices in rings of increasing distance from the start. DFS has none of these path-shaped properties. In exchange, BFS finds shortest paths in unweighted graphs. The final chapter compares the two in detail.
Exercise
Using the same graph (A → B, A → C, B → D, B → E, C → F), add an edge D → F. In listed order, what order does DFS first reach vertices in starting from A, assuming it never enters a vertex twice? What happens if you run the unmodified explore function on this graph instead?
Show answer
The order becomes A, B, D, F, E, C. From D the search now follows D → F, then backtracks to D, then to B, and tries E. When it later reaches C, the only edge C → F leads to an already-explored vertex, so nothing new happens. The unmodified explore function has no memory, so it enters F twice: once under D and once under C. It prints a duplicate enter/leave pair for F but still terminates, because the graph has no cycle.
Exercise
During the trace of the original graph, what is the largest number of vertices on the current path at any moment, and which step reaches it? In general, what quantity of the graph determines this maximum?
Show answer
The maximum is 3, first reached at step 3 (A, B, D) and again at steps 5 and 9. In general, the stack grows as large as the longest path DFS follows from the start. With visited tracking that path can't repeat vertices, so it is at most V vertices long.
Exercise
Suppose you change the neighbor list of A to ["C", "B"] and leave everything else the same. Write the step-by-step current path column for the first five steps.
Show answer
Step 1: A. Step 2: A, C. Step 3: A, C, F. Step 4: A, C (F is a dead end). Step 5: A (C is exhausted). The next step follows A → B, giving A, B.