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

The tour of the knight (exercise 16.6). More...

Files

file  ADS/backtrack/KnightTour.h
 The tour of the knight (exercise 16.6): a path of the knight that visits every square of an \( n \times n \) board once.

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).

The definitions, the invariants and the costs of the area are in Theory of backtracking.

Function documentation

◆ knightTour()

std::optional< std::vector< std::vector< int > > > ADS::knightTour ( int n,
int x,
int y,
bool warnsdorff = true )
inline

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

In pseudocode (exercise 16.6), \( A \) the board, 0 on the squares not visited yet:

\[\class{pseudocode}{\begin{array}{r@{\quad}l} 1 & \textbf{function}\ \mathrm{knightTour}( n , x , y ) \cr 2 & \quad A \gets \text{an } n \times n \text{ board of zeros}\quad \triangleright\ A[ a ][ b ] \text{ the step that reaches the square} \cr 3 & \quad \textbf{return}\ A \text{ if } \mathrm{tour}( 0 , x , y ) \text{, else } \textbf{nil} \cr 4 & \textbf{function}\ \mathrm{tour}( k , a , b ) \cr 5 & \quad A[ a ][ b ] \gets k + 1;\ \textbf{if}\ k + 1 = n^2 \ \textbf{then return true} \cr 6 & \quad M \gets \text{the moves from } ( a , b ) \text{ to a free square, in the order of the book} \cr 7 & \quad \textbf{if}\ \mathit{warnsdorff}\ \textbf{then} \ \text{reorder } M \text{ stably, the target with the fewest free moves first} \cr 8 & \quad \textbf{foreach}\ ( a' , b' ) \in M\ \textbf{do}\ \textbf{if} \ \mathrm{tour}( k + 1 , a' , b' )\ \textbf{then return true} \cr 9 & \quad A[ a ][ b ] \gets 0;\ \textbf{return false}\quad \triangleright\ \text{no way on: the square is freed} \end{array}} \]

Precondition
\( ( x , y ) \) is on the board if \( n \ge 1 \)
Postcondition
a tour of moves of the knight from \( ( x , y ) \) (audit)