Pascal Source Code

{* eight-queens
 * Author: Hannes du Plooy 
 * Date: 20 Sep 2016      
 * Objective: To solve the following
 * Search for a chess board solution with 8 queens and no one
 * endangering any other. *}
program eightqueens;

var
    board : Array[0..7] Of Integer;
    i: Integer;
    j: Integer;

function EightQueens(line: Integer): Boolean;
var column: Integer;
    line2: Integer;
    endangered: Boolean;
begin
    if (line > 7) then begin
        EightQueens := true;
    end
    else begin
        EightQueens := false;
        for column := 0 To 7 do begin
            endangered := false;
            for line2 := 0 to line-1 do begin
                if (board[line2] = column) or (Abs(line-line2) = Abs(column-board[line2])) then begin
                    endangered := true;
                    break;
                end;
            end;
            if not endangered then begin
                board[line] := column;
                if EightQueens(line+1) then begin
                    EightQueens := true;
                    break;
                end;
            end;
        end;        
    end;
end;

begin
    if (EightQueens(0)) then begin
        for i := 0 to 7 do begin
            for j := 0 to 7 do begin
                if (board[i] = j) then begin
                    Write('Q');
                end
                else
                    Write('.');
            end;
            WriteLn('');
        end;
    end 
    else 
        Writeln('No Solution');    
end.