The Knight's Tour 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 solve the tour by hand. Click here to continue the tour of ZX BASIC programs.

A ZX Spectrum emulator running a BASIC Knight's Tour program

Jasper ZX Spectrum Emulator by Adam Davidson and Andrew Pollard

Click on the screen and enter 'run' to supply the coordinates of a starting square for the knight to begin a new tour.
The Sinclair BASIC program below will solve it without backtracking although the backtracking routines have been retained.


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

   5 REM program to use weighted grid memoir by Geoff Wearmouth.  
  10 PRINT TAB 8;"Knight's Tour 4": GO TO 9000: REM initialize and run

1000 REM recursive subroutine
1010 IF x>8 OR x<1 OR y>8 OR y<1 THEN RETURN
1020 IF b$(s,1)<>a$(y,x) THEN RETURN
1030 IF SCREEN$ (20-y*2,2+x*3)<>" " THEN RETURN
1040 PRINT AT 20-y*2,1+x*3; PAPER 5+((y+x)=INT ((y+x)/2)*2);(" " AND s<10); s
1050 IF s=64 THEN PRINT AT 21,8;"SOLVED IN ";m; " MOVES" : STOP
1060 LET s=s+1: LET b$(s)="23456789": LET m=m+1
1070 LET x=x+x2: LET y=y+y1: GO SUB 1000: LET y=y-y1: LET x=x-x2
1080 LET x=x+x2: LET y=y-y1: GO SUB 1000: LET y=y+y1: LET x=x-x2
1090 LET x=x+x1: LET y=y+y2: GO SUB 1000: LET y=y-y2: LET x=x-x1
1100 LET x=x+x1: LET y=y-y2: GO SUB 1000: LET y=y+y2: LET x=x-x1
1110 LET x=x-x1: LET y=y+y2: GO SUB 1000: LET y=y-y2: LET x=x+x1
1120 LET x=x-x1: LET y=y-y2: GO SUB 1000: LET y=y+y2: LET x=x+x1
1130 LET x=x-x2: LET y=y+y1: GO SUB 1000: LET y=y-y1: LET x=x+x2
1140 LET x=x-x2: LET y=y-y1: GO SUB 1000: LET y=y+y1: LET x=x+x2
1150 IF b$(s)>="0" THEN LET b$(s)=b$(s,2 TO ): GO TO 1070
1155 LET s=s-1 : REM obsolete backtracking path
1160 PRINT AT 20-y*2,1+x*3; PAPER 8;"  "
1170 RETURN

9000 INPUT "x(1-8): ";x, "y(1-8): ";y : REM starting square
9005 IF x>8 OR x<1 OR y>8 OR y<1 THEN GO TO 9000
9010 LET x1=1-(2 AND (x>4)) : LET x2=x1*2 
9020 LET y1=1-(2 AND (y>4)) : LET y2=y1*2 
9030 BORDER 4: CLS : LET s=1: LET m=1
9040 FOR i=19 TO 162 STEP 16: PLOT 28,i: DRAW INK 1;192,0: NEXT i
9050 FOR j=28 TO 230 STEP 24: PLOT j,19: DRAW INK 1;0,127: NEXT j
9060 DIM a$(8,8): DIM b$(65,8)
9070 FOR i=1 TO 8: READ a$(i): NEXT i
9075 GO SUB 1040

9100 REM perfect weighted grid discovered by James Weatherley.
9110 DATA "22433422"
9120 DATA "35644653"
9130 DATA "56788765"
9140 DATA "36899863"
9150 DATA "36899863"
9160 DATA "56788765"
9170 DATA "35644653"
9180 DATA "22433422"
Previous Page   Home