Sub topic 14
Path Finding and Backtracking Search
This chapter assumes you can write recursive DFS over an adjacency-list dictionary and that you understand the visited set from earlier chapters. It also assumes you are comfortable with Python lists and sets and with how the call stack unwinds when a function returns.
DFS answers more than "what can I reach?" Because the recursion always holds the current route from the start vertex, it can also answer "how do I get there?" and "what are all the ways to get there?" The second question leads to backtracking. Backtracking is a general search technique: build a candidate solution one choice at a time, and undo the last choice when it leads nowhere.
Finding One Path
To report a path rather than a yes/no answer, keep a list that mirrors the recursion. Append a vertex when you enter it. Pop it when you leave without having found the goal. When the goal is reached, the list holds exactly the route the recursion took.
def find_path(graph, start, goal):
visited = set()
path = []
def visit(node):
visited.add(node)
path.append(node)
if node == goal:
return True
for neighbor in graph[node]:
if neighbor not in visited and visit(neighbor):
return True
path.pop() # dead end: remove this vertex from the route
return False
return path if visit(start) else None
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": [], "E": []}
print(find_path(graph, "A", "E")) # ['A', 'C', 'E']
print(find_path(graph, "D", "A")) # NoneThe trace shows the mechanism. The path grows to ['A', 'B', 'D']. D has no way out, so it is popped, and then B is popped. The search then tries C, skips D because D is already visited, and reaches E.
The visited set here is global: once a vertex is marked, it stays marked for the rest of the search. That is safe when you only need one path. If a vertex failed to lead to the goal once, every vertex reachable from it has already been explored, so trying it again cannot help. The search still runs in O(V + E).
An alternative is to store a parent dictionary while you search and then walk backward from the goal. That works for both DFS and BFS. The explicit path list is simpler when you also want to backtrack, which is the next topic.
Enumerating All Simple Paths
A simple path is a path that never repeats a vertex. To list every simple path from start to goal, a global visited set gives wrong answers. After the first path reaches D, D stays marked, and every other path through D is skipped.
The fix is to track only the vertices on the current path, and to unmark a vertex when the recursion leaves it:
def all_simple_paths(graph, start, goal):
paths = []
path = [start]
on_path = {start}
def visit(node):
if node == goal:
paths.append(list(path)) # copy: path keeps changing
return
for neighbor in graph[node]:
if neighbor not in on_path:
path.append(neighbor) # choose
on_path.add(neighbor)
visit(neighbor) # explore
path.pop() # un-choose
on_path.remove(neighbor)
visit(start)
return paths
graph = {"A": ["B", "C"], "B": ["C", "D"], "C": ["D", "A"], "D": []}
print(all_simple_paths(graph, "A", "D"))
# [['A', 'B', 'C', 'D'], ['A', 'B', 'D'], ['A', 'C', 'D']]The edge C → A forms a cycle. on_path blocks it, because A is always on the current path. Without that check, the recursion would loop forever.
The diagram makes the cost visible. The search explores a tree of partial paths, and that tree can be exponentially larger than the graph. A complete graph on n vertices has more than (n − 2)! simple paths between two vertices. Enumeration is inherently expensive, and no visited trick removes that cost, because the output itself is that large.
| Goal | What to track | Unmark on return? | Time |
|---|---|---|---|
| Reachability or one path | Global `visited` | No | O(V + E) |
| All simple paths | Vertices on the current path | Yes | Exponential in the worst case |
| Constrained solutions (puzzles) | The partial solution's state | Yes | Exponential, reduced by pruning |
The Backtracking Template
The append / recurse / pop pattern above is the core of backtracking. It applies even when no graph is written down. The "vertices" are partial solutions, and the "edges" are the choices that extend them. The general shape is:
- If the partial solution is complete, record it.
- For each candidate choice, skip it if it breaks a constraint. Skipping early like this is called pruning.
- Otherwise apply the choice, recurse, and then undo the choice exactly.
The N-Queens puzzle shows the template at work. The task is to place n queens on an n × n board so that no two share a row, column, or diagonal. Each recursion level fills one row. Sets give O(1) conflict checks: squares on the same down-right diagonal share row - col, and squares on the same up-right diagonal share row + col.
def solve_n_queens(n):
solutions = []
cols = [] # cols[r] is the column of the queen in row r
used_cols, diag1, diag2 = set(), set(), set()
def place(row):
if row == n:
solutions.append(list(cols))
return
for c in range(n):
if c in used_cols or (row - c) in diag1 or (row + c) in diag2:
continue # prune: this square is attacked
cols.append(c)
used_cols.add(c)
diag1.add(row - c)
diag2.add(row + c)
place(row + 1)
cols.pop()
used_cols.remove(c)
diag1.remove(row - c)
diag2.remove(row + c)
place(0)
return solutions
print(solve_n_queens(4)) # [[1, 3, 0, 2], [2, 0, 3, 1]]
print(len(solve_n_queens(8))) # 92Pruning is what makes this practical. Trying every column in every row would mean 8⁸ ≈ 16.7 million placements for n = 8. Rejecting attacked squares as soon as they appear cuts the search to a few thousand recursive calls.
Common Errors
- Using a global visited set for enumeration. This silently drops valid paths. Use per-path state and unmark it on return.
- Appending
pathinstead of a copy. Every stored result then points to the same list, which ends up empty after the search unwinds. Storelist(path)orpath[:]. - Undo that does not mirror the choice. Every
addneeds its matchingremove, and everyappendits matchingpop, applied in the same branch. A missed undo corrupts every later branch in ways that are hard to trace. - Pruning too late. Checking constraints only at full depth turns a fast search into a brute-force one. Reject a partial solution as soon as it fails.
- Recursion depth. A path can be as long as V. Python's default recursion limit is about 1000 frames, so very long paths need the explicit-stack technique from the earlier chapter. In that version, each stack entry carries its own copy of the path, or an undo marker.
Exercise
In allsimplepaths, replace on_path with a global visited set that is never unmarked, keeping everything else the same. Using the example graph, which paths are returned, and why is one missing?
Show answer
Only [['A', 'B', 'C', 'D'], ['A', 'B', 'D']]... in fact only [['A', 'B', 'C', 'D']] is returned. After the first path, B, C, and D all stay marked. Back at B, the edge to D is skipped, and back at A, the edge to C is skipped. Vertices stay marked after their branch finishes, so later branches cannot reuse them, and every path that shares a vertex with an earlier path is lost.
Exercise
Modify find_path so it returns a path from start to goal that avoids a given set of forbidden vertices. What is the smallest change, and does the running time change?
Show answer
Initialize visited with the forbidden vertices, for example visited = set(forbidden), before calling visit(start), and return None immediately if start is forbidden. DFS then never enters those vertices. The running time stays O(V + E), because each vertex and edge is still examined at most once.
Exercise
You need to list every subset of [1, 2, 3] whose elements sum to 3. Describe the choice made at each recursion level, the pruning rule, and the undo step.
Show answer
Level i decides whether to include element i: either recurse without it, or append it, recurse, and pop it. Since all elements are positive, prune any branch whose running sum already exceeds 3. Record the current subset (as a copy) when the sum equals 3 after all elements have been decided. The results are [1, 2] and [3].