

Solve the eight queens puzzle.



You can extend the problem to solve the puzzle with a board of size   NxN.

For the number of solutions for small values of   N,   see   OEIS: A000170.



Related tasks

 A* search algorithm
 Solve a Hidato puzzle
 Solve a Holy Knight's tour
 Knight's tour
 Peaceful chess queen armies
 Solve a Hopido puzzle
 Solve a Numbrix puzzle
 Solve the no connection puzzle


$ include "seed7_05.s7i";
 
var array integer: board is 8 times 0;
var integer: solutionNum is 0;
 
const func boolean: safe (in integer: y) is func
  result
    var boolean: safe is TRUE;
  local
    var integer: i is 1;
  begin
    while i < y and safe do
      safe := board[y - i] <> board[y] and
              board[y - i] <> board[y] - i and
              board[y - i] <> board[y] + i;
      incr(i);
    end while;
  end func;
 
const proc: putBoard is func
  local
    var integer: y is 0;
  begin
    incr(solutionNum);
    writeln;
    writeln("Solution " <& solutionNum);
    for y range 1 to 8 do
      writeln("|_" mult pred(board[y]) <& "|Q" <& "|_" mult (8 - board[y]) <& "|");
    end for;
  end func;
 
const proc: main is func
  local
    var integer: y is 1;
  begin
    while y >= 1 do
      repeat
        incr(board[y]);
      until board[y] > 8 or safe(y);
      if board[y] <= 8 then
        if y < 8 then
          incr(y);
          board[y] := 0;
        else
          putBoard;
        end if;
      else
        decr(y);
      end if;
    end while;
  end func;