The Knight's Tour
Volume Number: 14 (1998)
Issue Number: 11
Column Tag: Programming Puzzles
The Knight's Tour
by F.C. Kuechmann
A seemingly simple problem with thousands of solutions
There is a class of problems that, though seemingly simple in concept, involve numbers so large that the time or material required for solution renders them effectively impossible to solve manually within a human lifetime. The "grains of wheat on a chessboard" described by Gamow [1988] is one of the simpler and more easily explained examples of this sort of problem. We start with a single grain of wheat on the first square of the board, two grains on the second, four on the third, eight on the fourth, and so on. Each square receiving twice the number of grains as the previous square, until all 64 squares are occupied. Simple enough, right? Gamow suggests that it would take the entire world's wheat production for 2000 years to fill the board! In this article we're going to look at a similar challenge and show how to solve it with your Macintosh.
The Problem
The "knight's tour" is another chessboard problem that involves deceptively large numbers (this one is simpler though - we don't need any wheat). In the game of chess the knight can move only in L-shaped patterns consisting of two squares one direction and a single square perpendicular to the direction of the first two. There are eight possible moves from any given starting square, shown in Figure 1. From the 16 squares at the middle of a chessboard all eight moves can be executed without leaving the board; Away from the center fewer moves are executable because the knight would end up off the board entirely. In general, a knight in row 1 or 8, or column 1 or 8, can execute only 4 moves. A knight in row 2 or 7, or column 2 or 7, can execute 6 moves. A knight on a corner square has only two executable moves.
Figure 1. The eight possible moves of a knight.
The object of the knight's tour is, from a given starting square, to visit each square on the board exactly once.
From many of the 64 possible starting squares no complete tours are possible, whereas others offer thousands. My experiments have shown that, if there is at least one complete tour from a given starting square, there is a large number of complete tours from that square.
Starting at square one, we test eight possible moves. Each time a move is executed, we must test another eight moves, then another eight, and another, until we have either visited all 64 squares or exhausted the possible moves. At square 63, eight moves must be considered. At square 62, 8^2 moves must be tested. More generally, at any given square n, the number of moves to be tested is 8^(64-n), with a significantly smaller number of executable moves. If the knight's tour were as straightforward as the grains of wheat problem, determining all possible solutions from any given starting square would be described by a geometric progression of 8+(8^2)+(8^3)..+(8^62)+(8^63) - or 8^64 tests. That is not a small number! In fact, we get eight new tests only when we actually execute a move, so the number of required tests is somewhat smaller.
A human with a chessboard, a knight, and a pad of paper to record moves, together with a well-conceived systematic method and fast hands, would require so much time to derive even a single solution that it is practically if not theoretically impossible using hand methods.
1 | 38 | 59 | 36 | 43 | 48 | 57 | 52 |
60 | 35 | 2 | 49 | 58 | 51 | 44 | 47 |
39 | 32 | 37 | 42 | 3 | 46 | 53 | 56 |
34 | 61 | 40 | 27 | 50 | 55 | 4 | 45 |
31 | 10 | 33 | 62 | 41 | 26 | 23 | 54 |
18 | 63 | 28 | 11 | 24 | 21 | 14 | 5 |
9 | 30 | 19 | 16 | 7 | 12 | 25 | 22 |
64 | 17 | 8 | 29 | 20 | 15 | 6 | 13 |
Figure 2. One complete knight's tour.
Niklaus Wirth [1976,1986] describes a trial-and-error approach to the problem using recursion and backtracking, with soucecode in Pascal [1976] and Modula-2 [1986]. Unlike a human, a computer can find solutions quite easily, although it can still take a great deal of time. With Wirth's method and CodeWarrior Pascal, the solution shown in Figure 2 requires 66,005,601 possible moves to be considered, 8,250,732 moves to be executed, and occupies 35 seconds of time on a PPC Mac 6500/225. A total of 107 solutions for the same starting square were found in just under two hours with 16,114,749,106 total position tests and 2,014,343,776 moves; 12 hours got more than a thousand solutions without testing more than a fraction of the possible moves. At that rate finding all solutions for the entire board would take a very long time. Because of symmetries, however, we could simply divide the board into four 16-square quadrants, Figure 3, and find the solutions for any quadrant, then calculate the solutions for the remaining quadrants by mirroring.
Figure 3. The board as quadrants.
Solutions for quadrant 2 mirror those for quadrant 1 on the vertical axis. Quadrants 3 and 4 mirror quadrants 1 and 2 on the horizontal axis.
The Program
The chess board occupies the leftmost 2/3 of the window, with a control panel on the right. Top left of the control panel are three times...
- total time
- time on current starting square
- time since the most recent solution was found.
Tour 1 has only number 1; Tour 2 has numbers 1 and 3.
Top right is the current rotation pattern for testing possible moves; the patterns are toggled between 1 and 2 by clicking the Pat button, and the position is selected by clicking the Rot button. Below the time are statistics on move tests, moves, backtracks, and the maximum backtrack level.
Buttons for starting, pausing, pattern and rotation selection, update board status, tour selection [eight options], and speed 1-9 follow at bottom right.
The EvUp/SolUp button toggles update status. In the default EvUp mode the board is updated whenever the events are tested, and those intervals are determined by the speed setting; in SolUp mode the board is updated only if and when a complete tour is achieved. Since testing for events and updating the board require large amounts of time relative to calculating the knight's moves, higher execution speeds offer less frequent event testing and board updating.
The Tours
The eight tour options are:
- Tour 1 - finds one solution from the starting square and terminates; starting square selected by clicking on it.
- Tour 2 - finds all solutions from starting square; starting square selected by clicking on it.
- Tour 3 - starts at row 1, column 1 and moves through the entire board; if a solution is found, the next square becomes the starting square.
- Tour 4 - starts at row 1, column 1 and moves through the entire board; finds all solutions for each square.
- Quad 1 - finds all solutions for upper left quadrant.
- Quad 2 - finds all solutions for upper right quadrant.
- Quad 3 - finds all solutions for lower left quadrant.
- Quad 4 - finds all solutions for lower right quadrant.
Menus
Several program options are selected by menu.
- The File menu offers Run and Quit options.
- The Delay menu allows selection of the pause after each complete tour. The minimum is no pause, the maximum 30 seconds, the default 1 second.
- The Time menu determines the maximum time spent touring from a given starting square. In the cases of tours 1 and 2, pursuit of solutions ceases at that point; with the other six tours execution continues at the next square. The minimum selection is 2 minutes; the maximum specific interval 4 weeks. The default in no time limit.
- The Save menu offers options of No save, Save as text, and Save as records. The default is No save.
Drawing the Chess Board
The empty chess board is drawn and optionally initialized by calling the procedure in Listing 1. It calls the code in Listing 2 64 times, passing row, column and flag values. The flag determines whether the global array ggChessBd, which stores the current moves, is affected. If the flag is TRUE, the array location ggChessBd[row,column] is set to zero. The flag is TRUE during initialization, FALSE during all other updates.
Listing 1.
ClearTheBoard
procedure ClearTheBoard(flag:boolean);
{clear the board by drawing blank squares at}
{all 64 positions}
var
row,column:integer;
begin
for column:=1 to ggN do
for row:=1 to ggN do
SnuffKnight(row,column,flag);
end;
The SnuffKnight procedure in Listing 2 erases the square at the location given by row and column by drawing a light or dark empty square.
Listing 2.
SnuffKnight
procedure SnuffKnight (row,column:integer;flag:boolean);
{erases the move number at the specified row and column}
{position by drawing an empty square there}
var
vOffset,hOffset,height,width:integer;
pictureRect:Rect;
thePicture:PicHandle;
begin
SetPort(ggKnightWindow);
ggTourRect:=ggKnightWindow^.portRect;
if column mod 2=0 then
begin
{even # columns}
if row mod 2=0 then
thePicture:=GetPicture(ggcDK_ERASE_ID)
else
thePicture:=GetPicture(ggcLT_ERASE_ID);
end
else
begin
{odd # columns}
if row mod 2>0 then
thePicture:=GetPicture(ggcDK_ERASE_ID)
else
thePicture:=GetPicture(ggcLT_ERASE_ID);
end;
pictureRect:=thePicture^^.picFrame;
hOffset:=(column-1) * ggcSQUARE_SIZE;
vOffset:=(row-1) * ggcSQUARE_SIZE;
height:=pictureRect.bottom-pictureRect.top;
width:=pictureRect.right-pictureRect.left;
PlacePict(ggTourRect,vOffset,hOffset,height,width);
DrawPicture(thePicture,ggTourRect);
if flag then
ggChessBd[row,column]:=0;
end;
Listing 3 shows how the board is refreshed after an update event. If the value in location ggChessBd[row,column] is non-zero (i.e. it holds a move number for the knight), that number is drawn by calling the DrawKnight code in Listing 4; Otherwise Listing 2 is called with a flag value of FALSE.
Listing 3.
UpDateBoard
procedure UpDateBoard;
var
row,column,index:integer;
begin
for row:=1 to ggN do
for column:=1 to ggN do
begin
index:=ggChessBd[row,column];
if index>0 then
DrawKnight(row,column,index)
else
SnuffKnight(row,column,FALSE);
end;
end;
Listing 4.
DrawKnight
procedure DrawKnight(row,column,index:integer);
{draws a square with a knight move # at the specified row}
{and column}
var
vOffset,hOffset,height,width:integer;
S:Str255;
begin
SetPort(ggKnightWindow);
ggTourRect:=ggKnightWindow^.portRect;
hOffset:=(column-1) * ggcSQUARE_SIZE;
vOffset:=(row) * ggcSQUARE_SIZE;
NumToString(index,S);
if index<10 then
begin
{selectively erase squares with 1-9 when backtracking}
if (ggIndex<10) and (ggMaxBak<ggNsqr) then
SnuffKnight(row,column,FALSE);
MoveTo(hOffset+20,vOffset);
end
else
MoveTo(hOffset+14,vOffset);
TextSize(20);
ForeColor(blackColor);
if column mod 2=0 then
begin
if row mod 2=0 then
BackColor(redColor)
else
BackColor(whiteColor);
end
else
begin
if row mod 2>0 then
BackColor(redColor)
else
BackColor(whiteColor);
end;
TextMode(srcCopy);
DrawString(S);
BackColor(whiteColor);
end;
The Core Procedure
Most of the work in Knight's Tour is accomplished in Listing 5a. Testing for events, tracking the time, updating the board and statistics is accomplished by calling Listing 5b. The variable index holds the move number, x and y the column and row numbers. Variable k counts the possible moves 1-8. The global arrays gDeltaX and gDeltaY hold the number of squares to be moved on the X and Y axes to get to the position to be tested. Those values are added to the current row and column values to get the position to be tested. If the new position is on the board (i.e. both row and column in the 1..8 range, Listing 5c) and that board location unoccupied (Listing 5d), the move is made (Listing 5e); then if we don't have a complete tour (Listing 5f) the code in Listing 5a calls itself to make the next move. If the tested move can't be executed, the next possible move is tested. When no more possibilities exist, we drop out of loop and backtrack.
Listing 5a.
Try
procedure Try(index,x,y:integer;var q:boolean);
var
k,column,row,dX,dY:integer;
q1:boolean;
begin
k:=0;
ggIndex:=index;
q1:=FALSE;
repeat
Inc(gLoopCount);
if gLoopCount>=ggUpdateInterval then
DoUpdates(index:integer);
Inc(gTests);
if gTests>=ggcTenTo7th then
begin
gTests:=0;
Inc(gTestOvr);
EraseTestCount;
UpdateTests(gTests,gTestOvr);
end;
Inc(k);
dX:=gDeltaX[k];
dY:=gDeltaY[k];
column:=x+dX;
row:=y+dY;
if SquareIsOnBoard(row,column) and
SquareNotOccupied(row,column) then
begin
MakeTheMove(row,column,index);
Inc(gMoves);
if gMoves>=ggcTenTo7th then
begin
gMoves:=0;
Inc(gMoveOvr);
EraseMoveCount;
UpdateMoves(gMoves,gMoveOvr);
end;
if not CompleteTour(index) then
begin
Try(index+1,column,row,q1);
if (not q1) and (not ggQuitFlag) then
begin
ggChessBd[row,column]:=0;
Inc(gBakTrax);
if gBakTrax>=ggcTenTo7th then
begin
gBakTrax:=0;
EraseBakTrax;
Inc(gBakOvr);
UpDateBakTrax(gBakTrax,gBakOvr);
end;
if index<gLowestSoFar then
begin
gLowestSoFar:=index;
ggMaxBak:=index;
UpdateLowestRecurse(gLowestSoFar);
end;
end;
end
else if ggTourNum in [1,3] then
begin
q1:=TRUE;
DoSolution(index,q1);
GetTime(gStime);
Inc(ggSolNum);
Inc(gSolNum);
UpdateSolNum(gSolNum);
DoTime;
end
else
begin
DoTime;
DoSolution(index,TRUE);
if ggTourNum>3 then
DrawElapsed(0,3);
ggChessBd[row,column]:=0;
GetTime(gStime);
Inc(ggSolNum);
Inc(gSolNum);
UpdateSolNum(gSolNum);
DoTime;
end;
end;
until (k>=ggcNumKnightMoves) or ggQuitFlag
or ggErrFlag or gTimeFlag or q1;
q:=q1;
end;
Listing 5b.
DoUpdates
procedure DoUpdates(index:integer);
begin
gLoopCount:=0;
repeat
if ggUpdateFlag or ggRedrawFlag then
begin
UpDateBoard;
UpdateStats(index);
Stall(ggStallVal);
ggRedrawFlag:=FALSE;
end;
HandleEvent;
DoTime;
until (not ggPauseFlag) or gTimeFlag;
end;
Listing 5c.
SquareIsOnBoard
function SquareIsOnBoard(row,column:integer):boolean;
begin
If (column in [1..ggN]) and (row in [1..ggN]) then
SquareIsOnBoard:=TRUE
else
SquareIsOnBoard:=FALSE;
end;
Listing 5d.
SquareNotOccupied
function SquareNotOccupied(row,column:integer):boolean;
begin
if ggChessBd[row,column]=0 then
SquareNotOccupied:=TRUE
else
SquareNotOccupied:=FALSE;
end;
Listing 5e.
MakeTheMove
procedure MakeTheMove(row,column,index:integer);
begin
ggChessBd[row,column]:=index;
end;
Listing 5f.
CompleteTour
function CompleteTour(index:integer):boolean;
begin
if index<ggNsqr then
CompleteTour:=FALSE
else
CompleteTour:=TRUE;
end;
Initializing the Offsets
The values in arrays gDeltaX and gDeltaY are initialized to -2,-1,1 or 2 by passing them to the procedure in Listing 6. Two conditions must be accomodated in the initialization: the move pattern 1-2 held in the variable ggPattern, and the rotation 1-8 of that pattern held in ggRot. The move values are held in two, two-by-eight integer constant arrays, cDeltaX and cDeltaY. Using ggPattern and ggRot as indices, the values are transfered from the constant arrays to the proper locations in deltaX and deltaY.
Listing 6.
InitDelta
{x value increases left-to-right}
{y value increases top-to-bottom}
procedure InitDelta(var deltaX,deltaY:ggDeltaType);
type
knightMoves=array[1..2,1..8] of integer;
const
cDeltaX:knightMoves=((-2,-1,1,2,2,1,-1,-2),
(2,1,-1,-2,-2,-1,1,2));
cDeltaY:knightMoves=((-1,-2,-2,-1,1,2,2,1),
(-1,-2,-2,-1,1,2,2,1));
var
n,m,p:integer;
begin
n:=ggRot;
m:=ggPattern;
for p:=1 to 8 do
begin
deltaX[p]:=cDeltaX[m,n];
deltaY[p]:=cDeltaY[m,n];
Inc(n);
if n>8 then
n:=1;
end;
end;
Displaying the Test Pattern
Displaying the testing order for possible moves in the upper right corner of the window and changing that display as the Pat and Rot buttons are clicked is handled by the code in Listing 7. Pattern 1 tests begin at 10 o'clock and rotate clockwise. Pattern 2 tests begin at 2 o'clock and rotate counter-clockwise. Listing 7a copies the test position numbers from integer constant array cPat1 or cPat2 into the display position array gRotPos. Display positions are numbered 1-8 starting at ten o'clock and moving clockwise. The value of rotation variable ggRot is used to index into the appropriate constant array, determined by the value of ggPattern. Listing 7b is then called.
Listing 7a.
DrawPattern
procedure DrawPattern;
type
patArray=array[1..15] of integer;
const
cPat1:patArray=(2,3,4,5,6,7,8,1,2,3,4,5,6,7,8);
cPat2:patArray=(4,3,2,1,8,7,6,5,4,3,2,1,8,7,6);
var
n,p:integer;
begin
p:=ggRot-1;
case ggPattern of
1:
begin
for n:=1 to 8 do
gRotPos[n]:=cPat1[n+(7-p)];
end;
2:
begin
for n:=1 to 8 do
gRotPos[n]:=cPat2[n+p];
end;
end; {case}
DrawPat;
end;
Listing 7b sets the text size and colors, then calls Listing 7c to clear the display rectangle. Next it calls Listing 7d to draw the grid of white lines. Finally, using the values stored in array gRotPos, it draws the test order numbers on the grid.
Listing 7b.
DrawPat
procedure DrawPat;
var
leftEdge,topEdge,squareSize,x,y,z,n:integer;
S:Str255;
const
cXoff:integer=6;
cYoff:integer=15;
begin
TextSize(gcPatSize);
ForeColor(whiteColor);
BackColor(blackColor);
ClearRotRect;
DrawMatrix;
BackColor(whiteColor);
leftEdge:=ggcClockLeft+gcPatLeft;
topEdge:=10;
TextMode(srcOr);
squareSize:=20;
S:='K';
x:=(2*squareSize)+cXoff;
y:=(2*squareSize)+cYoff;
MoveTo(leftEdge+x,topEdge+y);
DrawString(S);
for n:=1 to 8 do
begin
z:=gRotPos[n];
NumToString(z,S);
case n of
1:
begin
{position 1}
x:=cXoff;
y:=(squareSize)+cYoff;
MoveTo(leftEdge+x,topEdge+y);
DrawString(S);
end;
2:
begin
{pos 2}
x:=(squareSize)+cXoff;
y:=cYoff;
MoveTo(leftEdge+x,topEdge+y);
DrawString(S);
end;
3:
begin
{pos 3}
x:=(3*squareSize)+cXoff;
y:=cYoff;
MoveTo(leftEdge+x,topEdge+y);
DrawString(S);
end;
4:
begin
{pos 4}
x:=(4*squareSize)+cXoff;
y:=(squareSize)+cYoff;
MoveTo(leftEdge+x,topEdge+y);
DrawString(S);
end;
5:
begin
{pos 5}
x:=(4*squareSize)+cXoff;
y:=(3*squareSize)+cYoff;
MoveTo(leftEdge+x,topEdge+y);
DrawString(S);
end;
6:
begin
{pos 6}
x:=(3*squareSize)+cXoff;
y:=(4*squareSize)+cYoff;
MoveTo(leftEdge+x,topEdge+y);
DrawString(S);
end;
7:
begin
{pos 7}
x:=(squareSize)+cXoff;
y:=(4*squareSize)+cYoff;
MoveTo(leftEdge+x,topEdge+y);
DrawString(S);
end;
8:
begin
{pos 8}
x:=cXoff;
y:=(3*squareSize)+cYoff;
MoveTo(leftEdge+x,topEdge+y);
DrawString(S);
end;
end;
end;
ForeColor(blackColor);
TextMode(srcCopy);
end;
Listing 7c calls Listing 7e to set the boundaries of the display rectangle and clears it to black, then adds the pattern and rotation numbers at the bottom.
Listing 7c.
ClearRotRect
procedure ClearRotRect;
var
width,height,leftEdge,topEdge:integer;
myRect:Rect;
S:Str255;
begin
SetPort(ggKnightWindow);
myRect:=ggKnightWindow^.portRect;
leftEdge:=ggcClockLeft+gcPatLeft;
topEdge:=10;
width:=100;
height:=100;
SetRect(myRect,leftEdge,topEdge,width,height);
EraseRect(myRect);
NumToString(ggPattern,S);
S:=concat('Pattern #',S);
MoveTo(leftEdge+10,topEdge+height+gcPatSize+5);
DrawString(S);
NumToString(ggRot,S);
S:=concat('Rotation ',S);
MoveTo(leftEdge+10,topEdge+height+(gcPatSize*2)+10);
DrawString(S);
end;
Listing 7d.
DrawMatrix
procedure DrawMatrix;
var
leftEdge,topEdge,n:integer;
begin
leftEdge:=ggcClockLeft+gcPatLeft;
topEdge:=10;
for n:=1 to 4 do
begin
MoveTo(leftEdge+(20*n),topEdge);
Line(0,100);
end;
for n:=1 to 4 do
begin
MoveTo(leftEdge,(20*n)+topEdge);
Line(100,0);
end;
end;
Listing 7e.
SetRect
procedure SetRect(var myRect:Rect;
leftEdge,topEdge,width,height:integer);
begin
myRect.top:=topEdge+myRect.top;
myRect.bottom:=myRect.top+height+2;
myRect.left:=leftEdge+myRect.left;
myRect.right:=myRect.left+width;
end;
Running the Program
There are four options that cannot be changed once a tour is underway, although three can be used at default values. The three that can be used at defaults are whether or not to save solutions (Save menu), move test pattern (Pat button), and the rotation of that pattern (Rot button). The fourth, mandatory option, is the tour number. The amount of additional housekeeping required depends on your choice of tour. Tours 1 and 2 require selection of the starting square by clicking on it. The other six tours have fixed starting squares as described previously. Once a sufficient number of selections have been made, the Run button becomes active. Clicking on it starts the search for solutions.
The default speed, button 2, is deliberately rather slow, with frequent board updates and every move displayed. As speeds are increased by clicking higher-numbered buttons, updates and event tests come less frequently.
If you want to see some solutions as rapidly as possible, select Tour 2, pattern 1, rotation 5, speed 8, starting square row 1, column 8.
For additional information, see the operating manual with the aps.
Source Code
Source code for a Macified implementation of Wirth's algorithm for the knight's tour is supplied for CodeWarrior Professional Pascal. Those readers familiar with Dave Mark's books may notice some resemblances between the sourcecode and some of that found in Dave's books - things like some of the names of constants and general structure of the event loop. I used the Timer project from the Macintosh Pascal Programming Primer, Vol. 1, by Dave Mark and Cartwright Reed, as a "skeleton". Most of the overlying code is mine, but underneath there's a bit of Mark and Reed code doing some of the housekeeping.
Bibliography and References
- Gamow, George, One Two Three...Infinity, (New York: Dover Books, 1988).
- Wirth, Niklaus, Algorithms + Data Structures = Programs, (Englewood Cliffs NJ: Prentice-Hall, 1976).
- Wirth, Niklaus, Algorithms and Data Structures, (Englewood Cliffs NJ: Prentice-Hall, 1986).
F.C. Kuechmann is a hardware designer, programmer and consultant with degrees from the University of Illinois at Chicago and Clark College who is currently trying to find the time to do the soldering required to make the programmers' clock that he has designed so that he can read the time in hexadecimal. You can reach him at fk@aone.com.