POTW #14-09 Knight`s Magic Square

POTW #14-09 Knight’
s Magic Square
Finding A Knight’
s Hamiltonian Path On A Chessboard
John Snyder, FSA
October 16, 2013
12:00 EST
Problem
A knight’
s re-entrant path is a path a knight takes over a chess board where the knight hits every square
and does not repeat any squares (example in the picture). Let the successive squares that form the
knight’
s re-entrant path be denoted by the numbers from 1 to 64 consecutively, 1 being the starting
square and 64 being the square from which the knight plays its last move, connecting the squares 64
and 1. Can you find a knight’
s re-entrant path such that the associated numbers in each row and each
column add up to 260?
Solution
Summary Of Results
Here is such a valid knight’
s path around the chessboard:
2
KnightMagicSquareTour1409.nb
8
16
24
32
40
48
56
64
7
15
23
31
39
47
55
63
6
14
22
30
38
46
54
62
5
13
21
29
37
45
53
61
4
12
20
28
36
44
52
60
3
11
19
27
35
43
51
59
2
10
18
26
34
42
50
58
1
9
17
25
33
41
49
57
Note that the squares in the above graph are numbered using the vertex numbers assigned in the first
section of our analysis; these numbers do not represent the order of the knight’
s steps across the
board. The path starts at square #1 and ends at square #59 having followed an allowable knight’
s tour
to each of the 64 squares on the chessboard.
A Graph Theory Approach
We begin our analysis by drawing an 8´8 knight’
s tour graph showing all the possible moves a knight
can make around a chessboard.
KnightMagicSquareTour1409.nb
In[1]:=
Panel@gr = KnightTourGraph@8, 8,
EdgeStyle ® 8Gray, [email protected]<, VertexLabelStyle ® White,
VertexLabels ® Table@n ® Placed@"Name", 81  2, 7  16<D, 8n, 64<D,
VertexSize ® 0.5, VertexShapeFunction ® "Square", VertexStyle ® Darker@GrayD,
VertexSize ® 81 ® 0.2, 64 ® 0.2<, Background ® [email protected], 0.93, 0.68DDD
8
16
24
32
40
48
56
64
7
15
23
31
39
47
55
63
6
14
22
30
38
46
54
62
5
13
21
29
37
45
53
61
4
12
20
28
36
44
52
60
3
11
19
27
35
43
51
59
2
10
18
26
34
42
50
58
1
9
17
25
33
41
49
57
Out[1]=
Haanpaa and Ostergard calculated that there are 13 267 364 410 532 distinct Hamiltonian cycles for a
knight moving around an 8´8 chessboard. This number is far too vast for us to enumerate all the
possibilities. In an attempt to find a suitable solution we’
ll generate 1 million distinct Hamiltonian paths
and hope for the best.
path = FindHamiltonianCycle@gr, 1 000 000DPAll, All, 1T;
Here is the first path found:
First@pathD
81, 11, 17, 2, 12, 6, 16, 31, 48, 63, 46, 61, 44, 59, 49, 34, 28, 22, 32, 15, 5, 20,
26, 41, 58, 43, 60, 45, 62, 56, 39, 29, 23, 8, 14, 24, 7, 13, 3, 9, 19, 25, 10, 4,
21, 27, 42, 57, 51, 36, 53, 38, 55, 40, 30, 47, 64, 54, 37, 52, 35, 50, 33, 18<
We write a Mathematica function which returns True if we found a suitable path whose rows and
columns total to 260 and False otherwise.
test@path_D := Module@8m, rows, cols<,
m = Reverse@Transpose@Partition@Table@n, 8n, 1, 64<D, 8DDD;
m = ReplacePart@m, Thread@Flatten@Position@m, ðD & ž path, 1D ® Range@64DDD;
rows = Plus žž m;
cols = Plus žž Transpose@mD;
Union ž Join@rows, colsD Š 8260<D;
We test each path rotated through its 64 possible orders.
3
4
KnightMagicSquareTour1409.nb
Position@ParallelMap@Map@test, Table@RotateLeft@ð, nD, 8n, 0, 63<DD &, pathD, TrueD
8<
We were not lucky and found no solution using this method.
An Integer Programming Approach
Having failed using a Hamiltonian graph theory approach, we’
ll try to solve the problem from scratch by
using modified integer programming techniques.
Finding A Starting Magic Square
We first need to find an 8´8 magic square in which all rows and columns sum to the required number of
260. At this stage we don’
t care if the magic square contains a knight’
s tour, nor do we care about the
sum of the diagonals.
We’
ll use a set of binary 0 or 1 valued variables of the form xr,c,t where r is the row number, c is the
column number, and t is the turn or step number assigned to the given square. There are 4096 such
variables in the case of an 8´8 magic square. For illustrative purposes we’
ll employ a much simpler
4´4 magic square.
In[2]:=
rows = cols = 4;
Here are the variables.
In[3]:=
Out[4]=
vars = Flatten@Table@xr,c,t , 8r, 1, rows<, 8c, 1, cols<, 8t, 1, rows * cols<DD;
Length@varsD
256
Our first constraint is that each of these variables must be either 0 or 1.
In[5]:=
con1 = Thread@0 £ vars £ 1D;
Next we impose the second constraint which says that on any one of his steps the knight must be at
only one location on the board. In other words, the knight cannot be in two places at the same time.
In[6]:=
con2 = Thread@
Plus žž Flatten@Table@xr,c,t , 8r, 1, rows<, 8c, 1, cols<, 8t, 1, rows * cols<D, 1D Š 1D;
A third constraint requires that each square on the board is visited exactly once during the course of the
knight’
s tour.
In[7]:=
con3 = Flatten@Table@Sum@xr,c,t , 8t, 1, rows * cols<D Š 1, 8r, 1, rows<, 8c, 1, cols<DD;
Our fourth constraint is that the rows each sum to the magic constant. In the case of the simple 4´4
square this magic constant is 34.
In[8]:=
con4 = Map@ð Š 34 &,
Plus žž Table@Sum@t xr,c,t , 8t, 1, rows * cols<D, 8r, 1, rows<, 8c, 1, cols<DD;
The fifth constraint is that the columns must sum to this same magic constant.
In[9]:=
con5 = Map@ð Š 34 &,
Plus žž Table@Sum@t xr,c,t , 8t, 1, rows * cols<D, 8c, 1, rows<, 8r, 1, cols<DD;
The domain of these binary variables is over the integers.
In[10]:=
domain = 8Element@vars, IntegersD<;
Since we care only that the constraints of the magic square are satisfied, we will employ a dummy
objective function of 1.
KnightMagicSquareTour1409.nb
Since we care only that the constraints of the magic square are satisfied, we will employ a dummy
objective function of 1.
In[11]:=
obj = 81<;
Mathematica can solve this simple 4´4 problem almost instantly.
In[12]:=
sol = DeleteCasesA
NMinimize@Join@obj, con1, con2, con3, con4, con5, domainD, varsDP2T, x_,_,_ ® 0E
Out[12]=
8x1,1,12 ® 1, x1,2,5 ® 1, x1,3,4 ® 1, x1,4,13 ® 1, x2,1,2 ® 1, x2,2,7 ® 1, x2,3,15 ® 1, x2,4,10 ® 1,
x3,1,11 ® 1, x3,2,6 ® 1, x3,3,14 ® 1, x3,4,3 ® 1, x4,1,9 ® 1, x4,2,16 ® 1, x4,3,1 ® 1, x4,4,8 ® 1<
And here is our 4´4 magic square.
In[13]:=
Out[14]=
sq4 = PartitionAIsol . x_,_,t_ ® tMPAll, 1T, 4E;
Grid@sq4, Frame ® AllD
12 5 4 13
2 7 15 10
11 6 14 3
9 16 1 8
We note that all the rows sum to the same value.
In[15]:=
Out[15]=
Plus žž sq4
834, 34, 34, 34<
And all the columns also sum to this same value.
In[16]:=
Out[16]=
Plus žž Transpose@sq4D
834, 34, 34, 34<
Applying this technique in the case of an 8´8 magic square is computationally taxing. Using parallel
kernels in a distributive computing grid we arrive, after a lengthy calculation, at the following magic
square.
In[17]:=
Out[18]=
m1 = 8845, 13, 20, 52, 61, 29, 4, 36<, 832, 64, 15, 47, 34, 2, 49, 17<,
83, 35, 62, 30, 19, 51, 46, 14<, 850, 18, 33, 1, 16, 48, 31, 63<,
856, 60, 9, 5, 40, 44, 25, 21<, 826, 22, 39, 43, 10, 6, 55, 59<,
841, 37, 24, 28, 57, 53, 8, 12<, 87, 11, 58, 54, 23, 27, 42, 38<<;
Grid@m1, Frame ® AllD
45
32
3
50
56
26
41
7
13
64
35
18
60
22
37
11
20
15
62
33
9
39
24
58
52
47
30
1
5
43
28
54
61
34
19
16
40
10
57
23
29
2
51
48
44
6
53
27
4
49
46
31
25
55
8
42
36
17
14
63
21
59
12
38
All the rows sum to 260 as they must.
5
6
KnightMagicSquareTour1409.nb
In[19]:=
Out[19]=
Plus žž m1
8260, 260, 260, 260, 260, 260, 260, 260<
And all the columns sum to 260 as well.
In[20]:=
Out[20]=
Plus žž Transpose@m1D
8260, 260, 260, 260, 260, 260, 260, 260<
An alternative and perhaps better technique might be to employ traditional methods for constructing a
magic square. Boden, for example, discusses these methods in some detail.
Modifying The Magic Square
Having found a traditional magic square as a starting point we now hope to modify the square so that it
represents a feasible knight’
s tour. Not every magic square can be modified in this way, but we’
ll proceed hoping for the best.
We can do this calculation by interchanging the orders of rows and/or columns. Note that such operations will not change the fact that the sum of the rows and columns is 260. To achieve acceptable speed
we write a compiled Mathematica function using C code that checks a magic square to see if the 1 ® 2
or 2 ® 1 knight’
s move rules are satisfied. This function returns a 1 if the modified magic square is a
valid knight’
s tour and 0 if it is not.
In[21]:=
cfTest = Compile@88m, _Integer, 2<<,
Module@8tab = Table@81, 2<, 864<D, last = 81, 1<<,
H* get steps for first 63 moves on the board *L
Do@tabPtT =
Sort@Abs@Flatten@Position@m, tDD - Flatten@Position@m, Mod@t + 1, 64, 1DDDDD,
8t, 1, 64<D;
H* check if step 64 is re-entrant wrapping around edge of board *L
last = Sort@Abs@Flatten@Position@Transposež RotateLeft@Transpose@mDD, 64DD Flatten@Position@Transposež RotateLeft@Transpose@mDD, Mod@65, 64, 1DDDDD;
H* if all steps are 81,2< we have a valid knight's tour *L
If@last Š 81, 2<, tabP64T = lastD;
If@Union@tabD Š 881, 2<<, 1, 0DD, CompilationTarget ® "C"D;
We also need a function to loop through all possible permutations of the rows and columns until we,
hopefully, find a magic square that contains a feasible knight’
s tour. The following function does this.
Unfortunately, this function cannot be compiled without additional fine tuning. We’
ll live with code in this
form recognizing that up to H8!L2 = 1 625 702 400 transformations may be necessary. Using a noncompiled function of this type on a fast computer it could take Mathematica up to 3.5 days to complete
the search. At this point we’
ll again cross our fingers and hope for the best!
In[22]:=
loop@m_D := Module@8rows, cols, m1, m2, cnt = 1<,
rows = cols = Permutations@Range@8D, 88<D;
Do@m1 = mProwsPrTT;
Do@m2 = Transpose@Transpose@m1DPcolsPcTTD;
If@cfTest@m2D Š 1, Print@m2DD, 8c, 1, Length@colsD<D,
8r, 1, Length@rowsD<DD;
We run the function as follows:
In[23]:=
loop@m1D
Luckily, Mathematica found the solution during an over night run of about 14.8 hours duration. The
solution was found to be:
KnightMagicSquareTour1409.nb
Luckily, Mathematica found the solution during an over night run of about 14.8 hours duration. The
solution was found to be:
In[24]:=
Out[25]=
m2 = 881, 48, 31, 50, 33, 16, 63, 18<, 830, 51, 46, 3, 62, 19, 14, 35<,
847, 2, 49, 32, 15, 34, 17, 64<, 852, 29, 4, 45, 20, 61, 36, 13<,
85, 44, 25, 56, 9, 40, 21, 60<, 828, 53, 8, 41, 24, 57, 12, 37<,
843, 6, 55, 26, 39, 10, 59, 22<, 854, 27, 42, 7, 58, 23, 38, 11<<;
Grid@m2, Frame ® AllD
1
30
47
52
5
28
43
54
48
51
2
29
44
53
6
27
31
46
49
4
25
8
55
42
50
3
32
45
56
41
26
7
33
62
15
20
9
24
39
58
16
19
34
61
40
57
10
23
63
14
17
36
21
12
59
38
18
35
64
13
60
37
22
11
As expected, the sum of the rows remains 260.
In[26]:=
Out[26]=
Plus žž m2
8260, 260, 260, 260, 260, 260, 260, 260<
As does the sum of the columns.
In[27]:=
Out[27]=
Plus žž Transpose@m2D
8260, 260, 260, 260, 260, 260, 260, 260<
The solution involves the following re-ordering of rows and columns in the original magic square found
in the prior section.
In[28]:=
rows = 84, 3, 2, 1, 5, 7, 6, 8<;
cols = 84, 6, 7, 1, 3, 5, 8, 2<;
We see that using this re-ordering we have found a valid solution.
In[30]:=
Out[30]=
Transposež Transpose@m1ProwsTDPcolsT Š m2
True
Note that the original magic square did not contain a knight’
s tour as indicated by the following function
returning 0.
In[31]:=
Out[31]=
cfTest@m1D
0
But the modified magic square we found using the above procedure does contain a knight’
s tour as we
see by the following function returning a 1.
In[32]:=
Out[32]=
cfTest@m2D
1
Now we recover the path we found and plot it on the original knight tour graph.
7
8
KnightMagicSquareTour1409.nb
In[33]:=
Out[33]=
In[37]:=
path = Map@8 HðP1T - 1L + ðP2T &,
Flatten@Position@Transpose@Table@8r, c<, 8r, 1, 8<, 8c, 1, 8<DD, ðDD & ž
HFlatten@Position@m2, ðDD & ž Range@64DLD
81, 11, 26, 20, 5, 15, 32, 22, 37, 47, 64, 54, 60, 50, 35, 41, 51, 57, 42, 36, 53,
63, 48, 38, 21, 31, 16, 6, 12, 2, 17, 27, 33, 43, 58, 52, 62, 56, 39, 45, 30, 24,
7, 13, 28, 18, 3, 9, 19, 25, 10, 4, 14, 8, 23, 29, 46, 40, 55, 61, 44, 34, 49, 59<
Panel@HighlightGraph@gr, PathGraph@pathDDD
8
16
24
32
40
48
56
64
7
15
23
31
39
47
55
63
6
14
22
30
38
46
54
62
5
13
21
29
37
45
53
61
4
12
20
28
36
44
52
60
3
11
19
27
35
43
51
59
2
10
18
26
34
42
50
58
1
9
17
25
33
41
49
57
Out[37]=
Note that the squares in the above graph are numbered using the vertex numbers assigned in the first
section of our analysis; these numbers do not represent the order of the knight’
s steps across the
board. The path starts at square #1 and ends at square #59 having followed an allowable knight’
s tour
to each of the 64 squares on the chessboard.
Thankfully, we are finished!
References
Boden, Jeremy, Magic Square, http://www.math.niu.edu/~rusin/known-math/98/magsq2
Cook, John D, A Knight’
s Tour Magic Square, http://www.johndcook.com/blog/2011/04/06/a-knightsmagic-square/
Haanpaa, H and Ostergard, P, Counting Hamiltonian Cycles In Bipartite Graphs, Department of Communications and Networking, Aalto University School of Electrical Engineering, P.O. Box 13000, 00076
Aalto, Finland, http://users.tkk.fi/~pat/papers/hamilton.pdf
Jellis, George Peter, Mayhematics.com, http://www.mayhematics.com