

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


(   ( printBoard
    =   board M L x y S R row line
      .   :?board
        & !ups:? [?M
        &   whl
          ' ( !arg:(?x.?y) ?arg
            & !M:?L
            & :?row:?line
            &   whl
              ' ( !L+-1:~<0:?L
                & !x+1:~>!M:?x
                & "---+" !line:?line
                & "   |" !row:?row
                )
            & "---+" !line:?line
            & " Q |" !row:?row
            &   whl
              ' ( !L+-1:~<0:?L
                & "---+" !line:?line
                & "   |" !row:?row
                )
            & "\n|" !row "\n+" !line !board:?board
            )
        & str$("\n+" !line !board)
    )
    ( queens
    =   hor ver up down ups downs a z A Z x y Q
      .   !arg:(?hor.?ver.?ups.?downs.?Q)
        &   !ver
          : (   
              & 1+!solutions:?solutions
              { Comment the line below if you only want a count. }
              & out$(str$("\nsolution " !solutions) printBoard$!Q)
              & ~  { Fail! (and backtrack to find more solutions)}
            |   #%?y
                ( ?z
                &   !hor
                  :   ?A
                      #%?x
                      ( ?Z
                      & !x+!y:?up
                      & !x+-1*!y:?down
                      & ~(!ups:? !up ?)
                      & ~(!downs:? !down ?)
                      &   queens
                        $ ( !A !Z
                          . !z
                          . !up !ups
                          . !down !downs
                          . (!x.!y) !Q
                          )
                      )
                )
            )
    )
& 0:?solutions
& 1 2 3 4 5 6 7 8:?H:?V   {You can edit this line to find solutions for other sizes.}
& ( queens$(!H.!V...) 
  | out$(found !solutions solutions)
  )
);