

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


100 PROGRAM "NQueens.bas"
110 TEXT 80
120 DO
130   INPUT PROMPT "Size of board (2-12): ":N$
140   LET N=VAL(N$)
150 LOOP UNTIL N>1 AND N<13
160 NUMERIC A(1 TO N),X(1 TO N),B(2 TO 2*N),C(-N+1 TO N-1)
170 LET SOL=0
180 CALL INIT(A):CALL INIT(B):CALL INIT(C)
190 CALL TRY(1)
200 PRINT SOL;"solutions."
210 END
220 DEF WRITE
230   LET S$="":LET SOL=SOL+1
240   FOR K=1 TO N
250     LET S$=S$&CHR$(64+K)&STR$(X(K))&"  "
260   NEXT
270   PRINT S$
280 END DEF
290 DEF TRY(I)
300   NUMERIC J
310   FOR J=1 TO N
320     IF A(J) AND B(I+J) AND C(I-J) THEN
330       LET X(I)=J:LET A(J),B(I+J),C(I-J)=0
340       IF I<N THEN
350         CALL TRY(I+1)
360       ELSE
370         CALL WRITE
380       END IF
390       LET A(J),B(I+J),C(I-J)=1
400     END IF
410   NEXT
420 END DEF
430 DEF INIT(REF T)
440   FOR I=LBOUND(T) TO UBOUND(T)
450     LET T(I)=1
460   NEXT
470 END DEF