Sub topic 3
The Choose, Explore, Unchoose Template
This chapter assumes you can write recursive Python functions with base cases, and that you have read the previous chapter on state-space trees. In a state-space tree, each node is a partial solution and each edge is one choice. Almost every backtracking algorithm in this tutorial walks that tree with the same three-step loop. Once you know that loop, the later problems differ only in which choices are allowed and when a path counts as complete.
The three steps
At each node, the algorithm looks at every choice still available and does the following for each one:
- Choose. Apply the choice to the shared partial solution, for example by appending to a list.
- Explore. Recurse to handle the rest of the problem from the new state.
- Unchoose. Reverse exactly what step 1 did, so the next choice starts from the same state.
Before the loop, the function checks whether the current state is a complete solution. If it is, the function records the solution and returns.
A concrete instance
The example below generates every string of length n over a small alphabet. Each level of the tree fixes one position. Each choice is one letter.
def all_strings(alphabet, n):
result = []
path = []
def backtrack():
if len(path) == n: # complete solution
result.append("".join(path))
return
for letter in alphabet: # each available choice
path.append(letter) # choose
backtrack() # explore
path.pop() # unchoose
backtrack()
return result
print(all_strings("ab", 3))
# ['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']The whole search shares a single path list. When backtrack() returns, path holds exactly what it held before the call. That property is called the call's invariant. The loop depends on it: the second letter is tried from the same prefix the first letter saw.
Mapping the template to a problem
To fit a new problem into the template, answer four questions:
| Question | In `all_strings` |
|---|---|
| What is the shared state? | `path`, the letters chosen so far |
| When is the state complete? | `len(path) == n` |
| What choices exist at this node? | Every letter in `alphabet` |
| How do you undo a choice? | `path.pop()` |
Later chapters change these answers. For subsets, every node counts as a solution. Permutations add a used array that has to be undone as well. With pruning, some choices get skipped before step 1.
Common errors
- Forgetting to unchoose. If you leave out
path.pop(),pathkeeps growing across sibling branches and the results come out wrong. - Unchoosing the wrong thing. The undo has to mirror the choose step exactly. If the choose step changes two structures, the unchoose step must restore both.
- Returning early from inside the loop. A
returnplaced after the recursive call skips the remaining choices. Only return early on purpose, such as when you need just one solution.
Exercise
Modify all_strings so it never places the same letter twice in a row, and give the output for all_strings("ab", 3).
Show answer
Inside the loop, before choosing, add if path and path[-1] == letter: continue. The choose, explore, and unchoose steps stay the same. The output is ['aba', 'bab'].
Exercise
Suppose path.pop() is deleted from all_strings. What does all_strings("ab", 2) return, and why?
Show answer
It returns ['aa'], because only the first path is ever recorded. After 'aa' is recorded, nothing is removed. Every later call sees a path of length 2 or more, so the check len(path) == n never matches again. The search still finishes, because the extra appends push path past length 2, but it records nothing else.