Sub topic 14
Path Finding and Backtracking Search
This chapter assumes you can already write recursive DFS with a visited set and that you know DFS costs O(V + E) on an adjacency list. It adds two things to that. The first is recording the path you followed. The second is undoing your choices so you can try other ones. That second habit is called backtracking.
Recording the Path to a Target
To find any route from start to target, keep a path list that matches the current recursion stack. Append a vertex when you enter it. Pop it when every route through it has failed. The search can stop as soon as it reaches the target.
def find_path(graph, start, target):
visited = set()
path = []
def visit(node):
visited.add(node)
path.append(node)
if node == target:
return True
for neighbor in graph[node]:
if neighbor not in visited and visit(neighbor):
return True
path.pop() # dead end: remove node from the current route
return False
return path if visit(start) else None
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["E"], "E": []}
print(find_path(graph, "A", "E")) # ['A', 'B', 'D', 'E']Here the visited set is global. Once a vertex fails to reach the target, no other route through that vertex can reach it either, so the search never needs to look at it again. That keeps the cost at O(V + E). The path you get back is a path, which is not necessarily the shortest one.
Enumerating Every Path
Listing all simple paths requires a different visited rule. A vertex that has already been explored can appear again on a different path. Only vertices on the current path are off limits, because revisiting one of them would create a loop. When the search returns from a vertex, it removes that vertex from the path and from the set of path vertices. That undo step is backtracking.
def all_simple_paths(graph, start, target):
paths = []
path = [start]
on_path = {start}
def extend(node):
if node == target:
paths.append(list(path)) # copy, because path keeps changing
return
for neighbor in graph[node]:
if neighbor not in on_path:
path.append(neighbor) # choose
on_path.add(neighbor)
extend(neighbor) # explore
path.pop() # un-choose
on_path.remove(neighbor)
extend(start)
return paths
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["E"], "E": []}
for p in all_simple_paths(graph, "A", "E"):
print(p)
# ['A', 'B', 'D', 'E']
# ['A', 'C', 'D', 'E']
# ['A', 'C', 'E']In this tree, D appears twice because two different paths pass through it. The cost of the search is the size of this tree. That size can grow exponentially in V, because some graphs have exponentially many simple paths.
The General Backtracking Template
The same choose, explore, un-choose pattern solves puzzles where the "graph" is implicit. Each vertex is a partial solution, and each edge is one more decision. Placing N queens, generating permutations, and solving Sudoku all fit this shape. Pruning is what makes these searches practical: return early as soon as a partial solution breaks a constraint, so the search never expands the subtree below it.
| Goal | Visited rule | Cost |
|---|---|---|
| Any path | Global, never cleared | O(V + E) |
| All simple paths | Current path only, undone on return | Exponential in the worst case |
| Constraint puzzle | Current partial solution, with pruning | Depends on how much pruning removes |
Exercise
In allsimplepaths, suppose you replace on_path with a global visited set that is never cleared. What does the function return for the example graph from A to E, and why?
Show answer
It returns only [['A', 'B', 'D', 'E']]. The first branch marks B, D, and E as visited. When the search later tries C, both of C's neighbors (D and E) are already marked, so it never builds the paths A-C-D-E or A-C-E.
Exercise
Why does findpath never pop a vertex from visited, while allsimplepaths does remove vertices from onpath?
Show answer
findpath only needs one path. A vertex that failed once will fail again, so remembering it saves work. allsimple_paths needs every route, and a vertex can belong to several different paths. Only vertices on the current path must be blocked, to prevent loops.