Algorithms and Data Structures
Algorithms and Data Structures
Algorithms and Data Structures
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
N.Wirth. <strong>Algorithms</strong> <strong>and</strong> <strong>Data</strong> <strong>Structures</strong>. Oberon version 115<br />
data representation which makes checking as simple as possible. The best recipe is to represent as directly<br />
as possible that information which is truly relevant <strong>and</strong> most often used. In our case this is not the position<br />
of the queens, but whether or not a queen has already been placed along each row <strong>and</strong> diagonals. (We<br />
already know that exactly one is placed in each column k for 0 ≤ k < i.) This leads to the following choice<br />
of variables:<br />
VAR<br />
where<br />
x: ARRAY 8 OF INTEGER;<br />
a: ARRAY 8 OF BOOLEAN;<br />
b, c: ARRAY 15 OF BOOLEAN<br />
x i denotes the position of the queen in the i-th column;<br />
a j means "no queen lies in the j-th row";<br />
b k means "no queen occupies the k-th /-diagonal;<br />
c k means "no queen sits on the k-th \-diagonal.<br />
We note that in a /-diagonal all fields have the same sums of their coordinates i <strong>and</strong> j, <strong>and</strong> that in a \-<br />
diagonal the coordinate differences i-j are constant. The appropriate solution is shown in the following<br />
program Queens. Given these data, the statement SetQueen is elaborated to<br />
x[i] := j; a[j] := FALSE; b[i+j] := FALSE; c[i-j+7] := FALSE<br />
the statement RemoveQueen is refined into<br />
a[j] := TRUE; b[i+j] := TRUE; c[i-j+7] := TRUE<br />
The field is safe if it lies in a row <strong>and</strong> in diagonals which are still free. Hence, it can be expressed<br />
by the logical expression<br />
a[j] & b[i+j] & c[i-j+7]<br />
This allows one to formulate the procedures for enumeration of safe rows j for the i-th queen by analogy<br />
with the preceding example.<br />
This completes the development of this algorithm, that is shown in full below. The computed solution is x<br />
= (1, 5, 8, 6, 3, 7, 2, 4) <strong>and</strong> is shown in Fig. 3.8.<br />
0<br />
1<br />
2<br />
3<br />
4<br />
5<br />
6<br />
7<br />
0 1 2 3 4 5 6 7<br />
Fig. 3.8. A solution to the Eight Queens problem