Closed Knight's Tour in Prolog
Prolog code: knight.pl
uses CLP(FD) constraints
to model the problem. In particular,
the circuit/1 constraint is used to describe a
Hamiltonian circuit of the following graph:
For example, in the case of a 6×6 board, the underlying
graph looks as follows:
- one node per board position
- one edge between those nodes that can be reached via
You need SWI-Prolog >=
5.8.0 (recommended: latest git version). Start it with
$ swipl knight.pl
Example queries that you can try:
?- n_tour(N, Ts), maplist(label, Ts).
?- n_tour(N, Ts), maplist(label, Ts), print_tour(Ts).
?- show(8, [ff], Ts).
?- show(N, [ff], Ts), print_tour(Ts).
Sample solutions for N = 6, 8, 12, 16:
Challenges: Find solutions for large boards. Find good labeling and
allocation strategies. ...
Exercise: Modify the code so that it describes knight's
tours that are not necessarily closed. Hint: Introduce a dummy
node from which a tour may start.
More about Prolog