Queens Problem
Queens Problem
Queens Problem
94
Fig. 8.3.
8 queens problem
8 queens problem is t o place eight queens on a n 6* 8 chessboard so that no two queen
are placedat attacking position, i.e., they wi not placed on the same row, column, or diagonal
Let us number t h e rows and columns or the chessboardI through 8. Since each quee
Column
3 5 6
91
92
7 3 93
Row 4 4
Q5
96
97
O
98
Fig. 8.4.
Now we testwhether two queens are on the same
the
diagonal the every element will be on
same diagonal that runs from the upper left top lower right if it has the same value of
(row-column).
For
example, in the Fig. 8.5, consider the queen at (3, 1).
The positions that are
diagonal to this queen (running from the upper left to the lower
right) are 1)
(3, (4, 2), (5, 3), (6, 4), (7, 5) and (8, 6). All these position have the
(Row -Column), as 3-1 2, value 2for
4-2 2, 5-3 2, 6-4 2, 7-5 2, and 8-6 2. Similarly
= =
=
Now, suppose two queens are placed at positions (,J) and (m, n). Then by the above they
are on the same diagonal only if.
Backtracking 297
Fig. 8.5.
i - j = m -n or i+j=m + n
Then the first equation implies that
(2
j-n = i - m 7
The second equation implies that ( 4 , 2
j - n = m-i
Therefore two queens lies on the same diagonal if and only if,
(1
i-nl = li - m|
N-QUEENS (k, n)
1. For i - 1 to n
x[k]
n) then
if (k =
do PRINT x[1..n])
+ 1, n)
elseN-QUEENS(k
PLACE (k, i)
k-1
1. For j - 1 to ) =
Abs1-k))) then
2. do if (x[i] = i) or (Abs(xG]
return false
4. return true