

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


 
* N queens problem
* Set N to the desired number.  The program prints out all solution boards.
	N = 5
	NM1 = N - 1; NP1 = N + 1; NSZ = N * NP1; &STLIMIT = 10 ** 9; &ANCHOR = 1
	DEFINE('SOLVE(B)I')
* This pattern tests if the first queen attacks any of the others:
	TEST = BREAK('Q') 'Q' (ARBNO(LEN(N) '-') LEN(N) 'Q'
+	      | ARBNO(LEN(NP1) '-') LEN(NP1) 'Q'
+	      | ARBNO(LEN(NM1) '-') LEN(NM1) 'Q')
	P = LEN(NM1) . X LEN(1); L = 'Q' DUPL('-',NM1) ' '
	SOLVE()        :(END)
SOLVE	EQ(SIZE(B),NSZ) 	    :S(PRINT)
* Add another row with a queen:
	B = L B
LOOP	I = LT(I,N) I + 1 :F(RETURN)
	B TEST :S(NEXT)
	SOLVE(B)
* Try queen in next square:
NEXT	B P = '-' X :(LOOP)
PRINT	SOLUTION = SOLUTION + 1
	OUTPUT = 'Solution number ' SOLUTION ' is:'
PRTLOOP B LEN(NP1) . OUTPUT = :S(PRTLOOP)F(RETURN)
END
 