

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


#COMPILE EXE
#DIM ALL
 
SUB aux(n AS INTEGER, i AS INTEGER, a() AS INTEGER, _
        u() AS INTEGER, v() AS INTEGER, m AS QUAD)
 
    LOCAL j, k, p, q AS INTEGER
    IF i > n THEN
        INCR m
        FOR k = 1 TO n : PRINT a(k); : NEXT : PRINT
    ELSE
        FOR j = i TO n
            k = a(j)
            p = i - k + n
            q = i + k - 1
            IF u(p) AND v(q) THEN
                u(p) = 0 : v(q) = 0
                a(j) = a(i) : a(i) = k
                CALL aux(n, i + 1, a(), u(), v(), m)
                u(p) = 1 : v(q) = 1
                a(i) = a(j) : a(j) = k
            END IF
        NEXT
    END IF
END SUB
 
FUNCTION PBMAIN () AS LONG
    LOCAL n, i AS INTEGER
    LOCAL m AS QUAD
    IF COMMAND$(1) <> "" THEN
        n = VAL(COMMAND$(1))
        REDIM a(1 TO n) AS INTEGER
        REDIM u(1 TO 2 * n - 1) AS INTEGER
        REDIM v(1 TO 2 * n - 1) AS INTEGER
        FOR i = 1 TO n
            a(i) = i
        NEXT
        FOR i = 1 TO 2 * n - 1
            u(i) = 1
            v(i) = 1
        NEXT
        m = 0
        CALL aux(n, 1, a(), u(), v(), m)
        PRINT m
    END IF
END FUNCTION