Backtracking
Try a choice, explore what follows, and undo it before trying another.
backtracking, choices, recursion, searchTry a path and come back
Imagine choosing a route through a maze. When one choice has been explored, return to the last fork and try another. You do not need to start the whole maze over each time.
Backtracking builds a candidate one choice at a time. It explores what follows a choice, then undoes that choice before trying another. It can skip a branch early when it can prove that branch cannot lead to a valid answer.
Why use it and where it helps
This pattern helps explore possible arrangements, puzzle answers, and routes. It is a way to organise a search, not a promise that the search will be quick. The example below explores every path; it does not prune any branches.
Follow the choices
Choose A or B twice. Repeats are allowed.
start
A -> AA, AB
B -> BA, BB
After recording AA, remove the second A. The path is A again, ready to try B and record AB. Then remove the first A before starting the B branch. Recursion keeps track of the unfinished choices.
See the reasoning
Follow the example one step at a time
Choose A or B twice, undoing choices to explore every path. This is a prepared teaching demonstration, not live code execution.
Start
path: empty answers: none
There are two choices for each of two positions.
Python illustration
def paths(length):
answers = []
path = []
def explore():
if len(path) == length:
answers.append(path.copy())
return
for choice in ["A", "B"]:
path.append(choice)
explore()
path.pop()
explore()
return answers
print(paths(2))
print(paths(0))
Prepared output — not live execution:
[['A', 'A'], ['A', 'B'], ['B', 'A'], ['B', 'B']]
[[]]
The example assumes a non-negative integer length. Length zero has one
possible path: the empty path. A negative length never reaches the stopping
condition, so validate inputs when accepting them from elsewhere. Copy the
finished path because the shared path list changes during backtracking.
Time, space, and common mistakes
For length n, there are 2**n answers and each copied answer has n items.
Producing and storing them takes O(n × 2ⁿ) time and output space for positive
n, plus O(n) path and call-stack space. Python also limits recursion depth.
Forgetting to undo a choice mixes branches; forgetting the copy lets later
changes alter saved answers. Pruning can reduce explored branches, but only
when the skipped choices cannot contain a wanted answer.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
