home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Big Blue Disk 22
/
bbd22.zip
/
QUEENS.PAS
< prev
next >
Wrap
Pascal/Delphi Source File
|
1988-01-26
|
2KB
|
63 lines
{QUEENS.PAS = program to solve the
8-queens problem by John Sigle 1/24/88 }
PROGRAM EightQueens( Input, Output );
VAR K: INTEGER;
Success: Boolean;
InRow: ARRAY[1..8] OF BOOLEAN;
InDiag1: ARRAY[2..16] OF BOOLEAN;
InDiag2: ARRAY[-7..7] OF BOOLEAN;
QueenPos: ARRAY[1..8] OF INTEGER;
PROCEDURE Try( Col: INTEGER );
VAR Row: INTEGER;
BEGIN { Try to place a queen in column Col }
Row := 0;
REPEAT { Try each row }
Row := Row+1;
Success := FALSE;
IF {Test position} NOT (InDiag1[Col+Row]
OR InDiag2[Col-Row] OR InRow[Row]) THEN
BEGIN
{ Set the queen }
QueenPos[Col] := Row;
InRow[Row] := TRUE;
InDiag1[Col+Row] := TRUE;
InDiag2[Col-Row] := TRUE;
IF Col<8 THEN
BEGIN { Try to place another }
Try( Col+1 );
IF NOT Success THEN
BEGIN { Remove this queen }
QueenPos[Col] := 0;
InRow[Row] := FALSE;
InDiag1[Col+Row] := FALSE;
InDiag2[Col-Row] := FALSE
END
END
ELSE Success := TRUE
END
UNTIL Success OR (Row=8)
END; { of Try }
BEGIN { Main program }
{ Initialize indicators }
FOR K := 1 TO 8 DO InRow[K] := FALSE;
FOR K := 2 TO 16 DO InDiag1[K] := FALSE;
FOR K := -7 TO 7 DO InDiag2[K] := FALSE;
FOR K := 1 TO 8 DO QueenPos[K] := 0;
{ Try to find a solution }
TRY( 1 );
{ Print the solution }
IF Success THEN
FOR K := 1 TO 8 DO WRITE(QueenPos[K]);
WRITELN
END. { of EightQueens }