The Eight Queens Problem solved in Classic BASIC

Sorry, this browser is not Java(tm) enabled.

It either cannot run Java(tm) applets, or the running of applets is currently disabled in your browser.

 BASIC 

 EDIT               	F1
 CAPS LOCK          	F2
 LEFT               	F5, SHIFT+LEFT
 DOWN               	F6, SHIFT+DOWN
 UP                 	F7, SHIFT+UP
 RIGHT              	F8, SHIFT+RIGHT
 GRAPHICS MODE      	F9

  Click on the Screen  and enter 'run' for another go.    

Click here to continue the tour of ZX BASIC programs.

A ZX Spectrum emulator solving the BASIC Eight Queens program

Jasper ZX Spectrum Emulator by Adam Davidson and Andrew Pollard

The ancient challenge to place eight queens on the chessboard, so that no piece is attacking another, is solved here in Sinclair BASIC using recursion and backtracking. The program pauses at the first solution but pauses only momentarily at subsequent solutions although the program keeps a count of solutions which is shown at the end.
The Sinclair BASIC program below will solve the problem by backtracking.


THE EIGHT QUEENS - an example of recursion in Sinclair BASIC.
     Note. The SCREEN$ functions returns the character at a screen coordinate.

   5 REM by Geoff Wearmouth, 2004
  10 CLS : PRINT TAB 10;"EIGHT QUEENS": GO TO 9000

1000 IF x then PRINT AT y,x;"Q"
1010 FOR i=1 TO x-1
1020 IF SCREEN$ (y,i)="Q" THEN RETURN : REM horizontal clash
1030 IF (y-i)>=1 THEN IF SCREEN$ (y-i,x-i)="Q" THEN RETURN : REM up diagonal
1040 IF (y+i)<=8 THEN IF SCREEN$ (y+i,x-i)="Q" THEN RETURN : REM down diagonal
1050 NEXT i
1060 IF x=8 THEN LET s=s+1: PRINT AT 21,0;"Solutions: ";s: PAUSE s-1: RETURN
1070 LET x=x+1
1080 LET y=1: GO SUB 1000: PRINT AT 1,x;" "
1090 LET y=2: GO SUB 1000: PRINT AT 2,x;" "
1100 LET y=3: GO SUB 1000: PRINT AT 3,x;" "
1110 LET y=4: GO SUB 1000: PRINT AT 4,x;" "
1120 LET y=5: GO SUB 1000: PRINT AT 5,x;" "
1130 LET y=6: GO SUB 1000: PRINT AT 6,x;" "
1140 LET y=7: GO SUB 1000: PRINT AT 7,x;" "
1150 LET y=8: GO SUB 1000: PRINT AT 8,x;" "
1160 LET x=x-1 : REM backtrack
1170 RETURN

9000 PAPER 8: LET y=0 : LET x=0: LET s=0
9010 FOR i=1 TO 8: FOR j=1 TO 8: REM chequerboard grid
9020 PRINT PAPER 6-((i+j)/2=INT ((i+j)/2));AT i,j;" ": NEXT j: NEXT i
9030 GO SUB 1000 : REM recursive subroutine
9040 REM END
Previous Page   Home