13 Recursive Backtracking
13 Recursive Backtracking
Lecture 13
Recursive Backtracking
3
Basic Idea
• We want to try every possibility to see if it’s a solution
– unless we already know it’s invalid
choice #1
option option
#1 option #3
#2
choice #1
option option
#1 option #3
#2
choice #2
option option
#1 option #3
#2
• We are presented with another choice (that is based on
the option we chose) 5
Basic Idea
• And this sequence of choices continues until:
– you decide you’ve made a bad choice somewhere along
the sequence and want to backtrack
– you decide you’ve arrived at a perfectly valid solution
6
8 Queens
• 8 Queens is a classic backtracking problem
1 2 3 4 5 6 7 8
11
8 Queens
• If we choose to place the queen in row #5, our decision
tree will look like this:
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
13
8 Queens
• It’s clear that we could explore the possible choices for
the first column with a loop:
19
N Queens
• Time to write our method
29