Sub topic 2
Go Deep, Then Backtrack: The Core Idea
This chapter assumes you can read basic Python and know what vertices and edges are. It also assumes you understand how recursive calls stack up. It builds on the adjacency-list representation from the previous chapter.
The strategy in one sentence
Depth-first search (DFS) starts at a vertex and follows one edge after another as far as it can. When it reaches a dead end, it backs up to the most recent vertex that still has an unexplored edge and continues from there.
Think of walking a maze with one rule: always take the next untried corridor. When you hit a wall, walk back to the last junction with an untried option. DFS does the same thing on a graph. It commits to a single path and only reconsiders when that path runs out.
A trace on a small tree
A tree has no cycles, so we can watch the strategy without worrying about revisiting vertices. That problem gets its own chapter next.
Starting at A, DFS goes to B, then straight down to D. D has no children, so the search backs up to B and tries E. E is also a dead end, so it backs up through B to A, then goes down to C and finally F.
| Step | Action | Current path |
|---|---|---|
| 1 | Enter A | A |
| 2 | Enter B | A → B |
| 3 | Enter D (dead end) | A → B → D |
| 4 | Back to B, enter E | A → B → E |
| 5 | Back to A, enter C | A → C |
| 6 | Enter F (dead end) | A → C → F |
| 7 | Back to A, done | A |
The visit order is A, B, D, E, C, F. The "current path" column matters most. At every moment DFS holds exactly one path from the start, and the vertices on it are the ones it can still back up to. That path behaves like a stack: you push a vertex when you go deeper and pop it when you back up.
Seeing it run
This short program prints each entry and exit, indented by depth, so you can watch the descents and the backtracking:
tree = {
"A": ["B", "C"],
"B": ["D", "E"],
"C": ["F"],
"D": [],
"E": [],
"F": [],
}
def explore(node, depth=0):
print(" " * depth + "enter " + node)
for child in tree[node]:
explore(child, depth + 1)
print(" " * depth + "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 leave line is a backtrack. The call stack holds the current path for you, which is why recursion fits DFS so naturally.
Where the idea breaks
On a general graph, two paths can lead to the same vertex, and a cycle can lead back to a vertex already on the current path. If you run explore unchanged on a graph with a cycle, it never finishes. The common mistake is to treat a graph like a tree. The fix is to remember which vertices you have already seen, and the next chapter covers it.
Common misconceptions
- "DFS finds the shortest path." It does not. It finds a path, often a long one, because it commits to depth first.
- "Backtracking means restarting." Backtracking returns only to the nearest vertex with untried edges. Work already done is kept.
Exercise
Given the tree {"R": ["X", "Y"], "X": ["Z"], "Y": ["P", "Q"], "Z": [], "P": [], "Q": []}, in what order does DFS from R enter the vertices, and what is the current path at the moment it enters P?
Show answer
The entry order is R, X, Z, Y, P, Q. When DFS enters P, the current path is R → Y → P, because X and Z have already been finished and popped off the path.
Exercise
Why is it enough for DFS to remember just one path (a stack) instead of every path it has tried?
Show answer
Once a vertex's subtree is fully explored, DFS never needs to return to it. It only needs the vertices it may still back up to, and those are exactly the ones on the current path from the start.