

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


' version 13-04-2017
' compile with: fbc -s console
Dim Shared As ULong count, c()
 
Sub n_queens(row As ULong, n As ULong, show As ULong = 0)
 
    Dim As ULong x, y
 
    For x = 1 To n
 
        For y = 1 To row -1
            If c(y) = x OrElse ((row - y) - Abs(x - c(y))) = 0 Then
                Continue For, For
            End If
        Next
 
        c(row) = x
        If row < n Then
            n_queens(row +1 , n, show)
        Else
            count += 1
 
            If show <> 0 Then
                For y = 1 To n
                    Print Using "###"; c(y);
                Next
                Print
            End If
 
        End If
 
    Next
 
End Sub
 
' ------=< MAIN >=------
 
Dim As ULong n = 5
ReDim c(n)
' n_queens(1, n, show = 0 only show total | show <> 0 show every solution
n_queens(1, n, 1)
Print Using "## x ## board, ##### solutions"; n; n; count
Print
 
For n = 1 To 14
    ReDim c(n)
    count = 0
    n_queens(1, n)
    Print Using "A ## x ## board has ######## solutions"; n; n; count
Next
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End