八皇后问题是一种典型的搜索与回溯算法问题。

Pascal 代码如下(来自《Free Pascal 语言与基础算法》):

program eight_queen;
var a:array[1..8] of integer;
    b,c,d:array[-7..16] of boolean;
    sum:integer;
    response:integer;

procedure print;
var i:integer;
begin
    writeln('sum=',sum);
    for i:= 1 to 8 do write(a[i]:4);        // output first case
end;

procedure search(t:integer);
var j:integer;
begin
    if t>8 then                                // recursive border
    begin
    inc(sum);                                // number of cases +1
    if sum <= 5 then print;                    // output first 5 cases
    exit;
end;
for j:= 1 to 8 do                            // 8 possible positions each row
    if b[j] and c[t+j] and d[t-j] then        // position proved ok
    begin                                    // put queen and set up corresbonding coordination
        a[t]:=j;                            // queen of row t is put on column j
        b[j]:=false;                        // occupy column j
        c[t+j]:=false;                        // occupy two diagonal lines
        d[t-j]:=false;
        search(t+1);                        // search next queen recursively
        b[j]:=true;                            // backtracking, current queen is taken up
        c[t+j]:=true;                        // cancel then sign of occupation on the corresponding column and diagonal line
        d[t-j]:=true;
    end;
end;

begin
    fillchar(b,sizeof(b),true);                // initializing array b,c,d with default value true
    fillchar(c,sizeof(c),true);
    fillchar(d,sizeof(d),true);
    sum:=0;
    search(1);                                // starting from queen 1
    writeln(' the total: ',sum);
    readln(response);
end.