Backtracking 1
Backtracking 1
Backtracking 1
Definition
• According to Wiki
2 2
Note that a state refers to the board with current sub-set of Queens placed on the board.
1 1 1
2 2
2
- We are unable to place the 4𝑡ℎQueen
3
- Backtracking to displace the 3𝑟 𝑑 Queen
1 1 1
2 2
2 2
1
2
4
Recursive Backtracking algorithm
procedure NQueens(𝑛, 𝑘)
integer X[1…n]
for 𝑙 ≔ 1 to 𝑛 do
if ( 𝑃𝑙𝑎𝑐𝑒(𝑘, 𝑙)) then
{
𝑋[𝑘] = 𝑙;
if (𝑘 = 𝑛) then
print 𝑋[𝑙], 𝑙 = 1,2,
…,𝑛
else
NQueens(𝑛, 𝑘 + 1);
}
Backtracking algorithm Contd..
procedure Place 𝑘, 𝑙
// Let (𝑗, 𝑋[𝑗]) represent the 𝑗 𝑡 ℎ Queen in
the
𝑋[𝑗]𝑡 ℎ column for 𝑗 = 1, 2, … , 𝑘 − 1.
forif𝑗 (≔(X[𝑗]
1 to=𝑘 𝑖)
− or
1 do
(𝑋 𝑗 = |𝑗 − 𝑘|) )
−𝑙
return false;
return
true;
Efficiency (𝑛!)
With n=4, T(n) = T(4) = 4! = 24
Practice Problem
Consider an (𝑛 × 𝑛) chess board where (𝑖, 𝑗)
represents a grid on the chess board. The
problem is to place several queens on the board
so that each grid (𝑖, 𝑗) is covered/attacked/seen
by at least one queen. Write a recursive
backtracking algorithm to minimize the number
of queens required to cover all the grids.
Reference
s
• Cormen, Thomas H.; Leirson, Charles E.; Rivest,
Ronald L.; Stein, Clifford (2009) Introduction to
Algorithms (3rd ed.). MIT Press and McGraw-Hill.