Algorithms
Lecture 2: Backtracking
’Tis a lesson you should heed,
Try, try again;
If at ﬁrst you don’t succeed,
Try, try again;
Then your courage should appear,
For, if you will persevere,
You will conquer, never fear;
Try, try again.
— Thomas H. Palmer,
The Teacher’s Manual: Being an Exposition
of an Efﬁcient and Economical System of Education
Suited to the Wants of a Free People
(1840)
When you come to a fork in the road, take it.
— Yogi Berra
2 Backtracking
In this lecture, I want to describe another recursive algorithm strategy called
backtracking
. A backtracking
algorithm tries to build a solution to a computational problem incrementally. Whenever the algorithm
needs to decide between two alternatives to the next component of the solution, it simply tries both
options recursively.
2.1
n
Queens
The prototypical backtracking problem is the classical
nQueens Problem
, ﬁrst proposed by German
chess enthusiast Max Bezzel in 1848 for the standard 8
×
8 board, and both solved and generalized to
larger boards by Franz Nauck in 1850. The problem is to place
n
queens on an
n
×
n
chessboard, so that
no two queens can attack each other. For readers not familiar with the rules of chess, this means that no
two queens are in the same row, column, or diagonal.
♕
♕
♕
♕
♛
♕
♛
♕
♛
♕
♛
♕
One solution to the 8 queens problem, represented by the array [4,7,3,8,2,5,1,6]
Obviously, in any solution to the
n
Queens problem, there is exactly one queen in each column. So
we will represent our possible solutions using an array
Q
[
1..
n
]
, where
Q
[
i
]
indicates the square in
column
i
that contains a queen, or 0 if no queen has yet been placed in column
i
. To ﬁnd a solution,
we will put queens on the board row by row, starting at the top. A
partial
solution is an array
Q
[
1..
n
]
whose ﬁrst
r

1 entries are positive and whose last
n

r
+
1 entries are all zeros, for some integer
r
.
The following recursive algorithm recursively enumerates all complete
n
queens solutions that are
consistent with a given partial solution. The input parameter
r
is the ﬁrst empty row. Thus, to compute
all
n
queens solutions with no restrictions, we would call R
ECURSIVE
NQ
UEENS
(
Q
[
1..
n
]
,1
)
.
1