

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


﻿bundle Default {
  class NQueens {
    b : static : Int[];
    s : static : Int;
 
    function : Main(args : String[]) ~ Nil {
      b := Int->New[8];
      s := 0;
 
      y := 0;
      b[0] := -1;
 
      while (y >= 0) {
        do {
          b[y]+=1;
        } 
        while((b[y] < 8) & Unsafe(y));
 
        if(b[y] < 8) {
          if (y < 7) {
            b[y + 1] := -1;
            y += 1;
          } 
          else {
            PutBoard();
          };
        } 
        else {
          y-=1;
        };
      };
    }
 
    function : Unsafe(y : Int) ~ Bool {
      x := b[y];
      for(i := 1; i <= y; i+=1;) {
        t := b[y - i];
        if(t = x | t = x - i | t = x + i) {
          return true;
        };
      };
 
      return false;
    }
 
    function : PutBoard() ~ Nil {
      IO.Console->Print("\n\nSolution ")->PrintLine(s + 1);
      s += 1;
      for(y := 0; y < 8; y+=1;) {
        for(x := 0; x < 8; x+=1;) {
          IO.Console->Print((b[y] = x) ? "|Q" : "|_");
        };
        "|"->PrintLine();
      };
    }
  }
}
 