Knight Rider

December 2, 2011

A classic problem in computing is the Knight’s Tour, in which a knight visits every square on a chessboard; the objective is to list the knight’s moves in order. There are two types of tours: cyclic (or closed), in which the final square is a knight’s jump away from the starting square, and acyclic (or open), where the final square is unconstrained. Knight’s tours are often given for generalized chessboards, such as 5-by-5 or 10-by-12, in addition to the standard 8-by-8 chessboard.

The simple solution is via backtracking: Make any valid move. Then make another move. And so on, until you have completed the tour. If at any point there are no valid moves, backtrack and choose an alternate move. The diagram below shows a sample 8-by-8 cyclic tour, and the list below the board shows the list of squares using row and column coordinates in the order they are visited:

Since the number of possible tours is very large, the simple solution will likely take a long time. In 1823, H. C. von Warnsdorff proposed the following heuristic: sort the valid moves according to the number of their successor moves, choosing first the move that has the least number of successors (choose randomly in the event of a tie). On small chessboards, say less than 10-by-10, Warnsdorff’s heuristic frequently eliminates backtracking entirely.

Your task is to write a program that finds a single Knight’s Tour on an n-by-n chessboard. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Like this:

LikeLoading...

Related

One Response to “Knight Rider”

You can find a somewhat more elegant version on http://www.telefonica.net/web2/koot/knight-rider-0.rkt. It requires DrRacket though. In this version the path-finder is abstracted from the actual problem. It could also be used for other computations requiring backtracking. It should not be too difficult to adapt the code to programming praxis.
Best wishes, Jos Koot