ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
KnightTour.h File Reference

The tour of the knight (exercise 16.6): a path of the knight that visits every square of an \( n \times n \) board once. More...

#include <algorithm>
#include "ADS/Contract.h"
#include <array>
#include <cstdlib>
#include <optional>
#include <utility>
#include <vector>
#include "ADS/backtrack/impl/KnightTour.tpp"

Go to the source code of this file.

Namespaces

namespace  ADS

Functions

std::optional< std::vector< std::vector< int > > > ADS::knightTour (int n, int x, int y, bool warnsdorff=true)
 a tour of the knight from \( ( x , y ) \) on an \( n \times n \) board, by backtrack, the moves in the order of the book or by the rule of Warnsdorff, as the board of the steps from 1; none for \( n < 1 \), where there is no board

Detailed description

The tour of the knight (exercise 16.6): a path of the knight that visits every square of an \( n \times n \) board once.

The procedure of the book tries the 8 moves in a fixed order and backtracks from the dead ends, which on an \( 8 \times 8 \) board may take very long; the rule of Warnsdorff tries first the moves to the squares with the fewest onward moves, and with it the backtrack seldom happens, a tour of a board of hundreds of squares in linear time. Both return the board with the step of each square, from 1, or nothing if there is no tour from the given square.

The contracts [see Contract.h]: the start is on the board, and the tour found moves as a knight from it (checked at level 3). The operations are defined in KnightTour.tpp.

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, exercise 16.6, https://algoritmicamente.it/materiali/libro/capitoli/cap16.pdf
H. C. von Warnsdorf, Des Roesselsprunges einfachste und allgemeinste Loesung, Schmalkalden, 1823
Author
Donato Meoli
Dipartimento di Informatica
Università di Pisa