Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Queens Problem

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Backtracking 295

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

be on a different row, we can without loss of generality assumequeen q, is to be placed on

rOw i for be renron


queen Droblem
e n problem can there for
can there
All the
solutions toeight column on which
represented as
8 tuples (x, X2
queen i is placed,
Xg), where x, is the one solution for 8
a 4 5 X6 Xz is given
below,
ueen problem
Analysis and Design of Algorithms
.296

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
= =
=

every element on the same diagonal that goes from


upper right to the lower left has the
same value
of (row +column).
Forexample, consider the queen at position (8, 3), then the
to this queen (running from positions that are diagonal
upper right to the lower left) are (7, 4), (6,
5), (5, 6), (4, 7) and
(3, 8). All these position have the value 11 for (Row + Column) as
8+3 =11, 7+ 4 =11,
6+5 11, 5 +6 11, 4 +7 =11 and 3 +8
=11
=

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

do if PLACE (K, i) then

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

You might also like