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
|
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
struct {
int x, y;
} moves[8] = {{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{1,-2},{-1,2},{-1,-2}};
void doTour(int board[][8], int brdSize, int, int, int);
int main()
{
int board[8][8];
int brdSize = 0;
do {
cout << ("Enter the size of chessboard (2 to 8): ");
cin >> brdSize;
} while (brdSize < 2 || brdSize > 8);
int startX = 0, startY = 0;
cout << "Enter the position of the Knight: ";
cin >> startX >> startY;
for (int x = 0; x < brdSize; x++)
for (int y = 0; y < brdSize; y++)
board[x][y] = -1;
doTour(board, brdSize, startX, startY, 0);
return 0;
}
void doTour(int board[][8], int brdSize, int x, int y, int step)
{
if (step == brdSize * brdSize) {
for (int x = 0; x < brdSize; x++) {
for(int y = 0; y < brdSize; y++)
cout << setw(2) << board[x][y] << ' ';
cout << '\n';
}
exit(0); // Only find first solution
}
if (x >= 0 && x < brdSize &&
y >= 0 && y < brdSize && board[x][y] == -1) {
board[x][y] = step;
for (int i = 0; i < 8; i++)
doTour(board, brdSize, x + moves[i].x, y + moves[i].y, step + 1);
board[x][y] = -1;
}
}
|