Latest revision as of 10:10, 2 December 2008

The Knight's Tour is a
mathematical problem involving a knight on a chessboard. The knight is
placed on the empty board and, moving according to the rules of chess,
must visit each square exactly once.

An efficient version (some 10x faster than the example Python solution) using continuations.

This is about as direct a translation of the Python algorithm as you'll get without sticking the whole thing in IO. The Python version prints the board and exits immediately upon finding it, so it can roll back changes if that doesn't happen. Instead, this version sets up an exit continuation using callCC and calls that to immediately return the first solution found. The Logic version below takes around 50% more time.

It seems the following pure functional (except for the final printout)
version of the search has almost the same performance as the Dan
Doel's latest version with the unboxed arrays and callCC. For the board of
size 40, Dan Doel's version takes 0.047s on my computer; the version
below takes 0.048s. For smaller boards, the difference is
imperceptible. Interestingly, the file sizes of the compiled
executables (ghc -O2, ghc 6.8.2) are similar too: 606093 bytes for Dan
Doel's version, and 605938 bytes for the version below.
The version below is essentially Dan Doel's earlier version. Since
the problem involves only pure search (rather than committed choice),
I took the liberty of substituting FBackTrack (efficient MonadPlus)
for LogicT. FBackTrack can too be made the instance of LogicT; there
has not been any demand for that though.