1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
#include <iostream>
#include <iomanip>
#include <array>
#include <random>
#define N 8 // number of squares in a row/column of the board
bool solveKnight();
void printBoard(std::array<std::array<int, N>, N>&);
bool validMove(std::array<std::array<int, N>, N>&, int, int);
int main() {
if ( solveKnight() )
std::cout << "Full tour!" << std::endl;
else
std::cout << "Not a full tour." << std::endl;
}
bool solveKnight() {
std::array<std::array<int, N>, N> board{};
std::array<int, N> horizontal = {2, 1, -1, -2, -2, -1, 1, 2};
std::array<int, N> vertical = {-1, -2, -2, -1, 1, 2, 2, 1};
std::default_random_engine engine{static_cast<unsigned long int>(time(0))};
std::uniform_int_distribution<int> randomRow{0, 7};
std::uniform_int_distribution<int> randomColumn{0, 7};
std::uniform_int_distribution<int> randomMove{0, 7};
int moveType, moveNumber{0}, currentRow, currentColumn, testRow, testColumn;
bool complete{false}, goodMove;
// place the knight at a random spot on the board
currentRow = randomRow(engine);
currentColumn = randomColumn(engine);
board[currentRow][currentColumn] = ++moveNumber;
while ( !complete ) {
int move = randomMove(engine);
testRow = currentRow + horizontal[move];
testColumn = currentColumn + vertical[move];
goodMove = validMove(board, testRow, testColumn);
if ( goodMove ) {
currentRow = testRow;
currentColumn = testColumn;
board[currentRow][currentColumn] = ++moveNumber;
}
}
if ( moveNumber == 64 ) {
printBoard(board);
return true;
}
printBoard(board);
return false;
}
void printBoard(std::array<std::array<int, N>, N>& board) {
for ( int i{0}; i < N; i++ ) {
for ( int j{0}; j < N; j++ ) {
std::cout << std::setw(3) << board[i][j];
}
std::cout << std::endl;
}
}
bool validMove(std::array<std::array<int, N>, N>& board, int row, int column) {
return ( row >= 0 && row < N && column >= 0 && column < N && board[row][column] == 0 );
}
|