

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


 
Module N_queens {
          Const l = 15  'number of queens
          Const b = False  'print option
          Dim a(0 to  l), s(0 to l), u(0 to 4 * l - 2)
          Def long n, m, i, j, p, q, r, k, t
          For i = 1 To l: a(i) = i: Next i
          For n = 1 To l
              m = 0
              i = 1
              j = 0
              r = 2 * n - 1
              Do {
                  i--
                  j++
                  p = 0
                  q = -r
                  Do {
                      i++
                      u(p) = 1
                      u(q + r) = 1
                      Swap a(i), a(j)
                      p = i - a(i) + n
                      q = i + a(i) - 1
                      s(i) = j
                      j = i + 1
                  } Until j > n Or u(p) Or u(q + r)
                  If u(p) = 0 Then {
                      If u(q + r) = 0 Then {
                          m++  'm: number of solutions
                          If b Then {
                              Print "n="; n; "m="; m
                              For k = 1 To n {
                                  For t = 1 To n {
                                      Print If$(a(n - k + 1) = t-> "Q", ".");
                                  }
                                  Print
                              }
                          }
                      }
                  }
                  j = s(i)
                  While j >= n And i <> 0 {
                            Do {
                                      Swap a(i), a(j)
                                      j--
                            }  Until j < i
                            i--
                            p = i - a(i) + n
                            q = i + a(i) - 1
                            j = s(i)
                            u(p) = 0
                            u(q + r) = 0
                  }
              } Until i = 0
              Print n, m  'number of queens, number of solutions
          Next n
}
N_queens
 