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
|
int solveKnightsTour(Board board, int row, int col, int move) {
int solution = 1;
//Validate that row and col are not out of bounds
//and validate that spot is not occupied
if (row < 0 || col < 0 || row > ROW - 1 || col > COL - 1 || board.chessboard[row][col] > 0) {
return 0;
};
board.chessboard[row][col] = move;
if(move == 25) {
//print the board
cout << '\n';
cout << "Solution # "<< solution << '\n';
cout << '\n';
for (int row = 0; row < ROW; row++) {
for (int col = 0; col < COL; col++) {
cout << board.chessboard[row][col] << ' ';
}
cout << endl;
}
return solution;
}
solution += solveKnightsTour(board, row + 2, col + 1, move + 1);
solution += solveKnightsTour(board, row + 1, col + 2, move + 1);
solution += solveKnightsTour(board, row - 1, col + 2, move + 1);
solution += solveKnightsTour(board, row - 2, col + 1, move + 1);
solution += solveKnightsTour(board, row - 2, col - 1, move + 1);
solution += solveKnightsTour(board, row - 1, col - 2, move + 1);
solution += solveKnightsTour(board, row + 1, col - 2, move + 1);
solution += solveKnightsTour(board, row + 2, col - 1, move + 1);
return solution;
};
int main() {
Board myBoard;
int totalSolutions = 0;
for (int x = 0; x < ROW; x++) {
for (int y = 0; y < COL; y++)
myBoard.chessboard[x][y] = 0;
}
cout << "Welcome to Knight's tour!" << '\n';
cout << '\n';
cout << "Current board size = " << ROW << " x " << COL << '\n';
cout << "Starting position is 2,2. " << '\n';
cout << '\n';
cout << "Thinking....." << '\n';
cout << '\n';
int totalSolutions = solveKnightsTour(myBoard, 2, 2, 1);
cout << "Number of solutions = " << totalSolutions << '\n';
return 0; // 0 is success, 1 is well probably an error
}
|