2020-04-18 10:43:43 +08:00
|
|
|
#include <iostream>
|
2020-05-30 07:26:30 +08:00
|
|
|
#define n 8
|
2019-11-27 23:07:55 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
A knight's tour is a sequence of moves of a knight on a chessboard
|
2020-05-30 07:26:30 +08:00
|
|
|
such that the knight visits every square only once. If the knight
|
|
|
|
ends on a square that is one knight's move from the beginning
|
|
|
|
square (so that it could tour the board again immediately, following
|
2019-11-27 23:07:55 +08:00
|
|
|
the same path), the tour is closed; otherwise, it is open.
|
|
|
|
**/
|
|
|
|
|
2018-10-02 03:35:40 +08:00
|
|
|
using namespace std;
|
2020-05-30 07:26:30 +08:00
|
|
|
bool issafe(int x, int y, int sol[n][n])
|
2018-10-02 03:35:40 +08:00
|
|
|
{
|
2020-05-30 07:26:30 +08:00
|
|
|
return (x < n && x >= 0 && y < n && y >= 0 && sol[x][y] == -1);
|
2018-10-02 03:35:40 +08:00
|
|
|
}
|
2020-05-30 07:26:30 +08:00
|
|
|
bool solve(int x, int y, int mov, int sol[n][n], int xmov[n], int ymov[n])
|
2018-10-02 03:35:40 +08:00
|
|
|
{
|
2020-05-30 07:26:30 +08:00
|
|
|
int k, xnext, ynext;
|
2018-10-02 03:35:40 +08:00
|
|
|
|
2020-05-30 07:26:30 +08:00
|
|
|
if (mov == n * n)
|
2018-10-02 03:35:40 +08:00
|
|
|
return true;
|
|
|
|
|
2020-05-30 07:26:30 +08:00
|
|
|
for (k = 0; k < 8; k++)
|
2018-10-02 03:35:40 +08:00
|
|
|
{
|
2020-05-30 07:26:30 +08:00
|
|
|
xnext = x + xmov[k];
|
|
|
|
ynext = y + ymov[k];
|
2018-10-02 03:35:40 +08:00
|
|
|
|
2020-05-30 07:26:30 +08:00
|
|
|
if (issafe(xnext, ynext, sol))
|
|
|
|
{
|
|
|
|
sol[xnext][ynext] = mov;
|
2018-10-02 03:35:40 +08:00
|
|
|
|
2020-05-30 07:26:30 +08:00
|
|
|
if (solve(xnext, ynext, mov + 1, sol, xmov, ymov) == true)
|
|
|
|
return true;
|
|
|
|
else
|
|
|
|
sol[xnext][ynext] = -1;
|
|
|
|
}
|
2018-10-02 03:35:40 +08:00
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
int main()
|
|
|
|
{
|
2020-05-30 07:26:30 +08:00
|
|
|
// initialize();
|
2018-10-02 03:35:40 +08:00
|
|
|
|
|
|
|
int sol[n][n];
|
2020-05-30 07:26:30 +08:00
|
|
|
int i, j;
|
|
|
|
for (i = 0; i < n; i++)
|
|
|
|
for (j = 0; j < n; j++) sol[i][j] = -1;
|
2018-10-02 03:35:40 +08:00
|
|
|
|
2020-05-30 07:26:30 +08:00
|
|
|
int xmov[8] = {2, 1, -1, -2, -2, -1, 1, 2};
|
|
|
|
int ymov[8] = {1, 2, 2, 1, -1, -2, -2, -1};
|
|
|
|
sol[0][0] = 0;
|
2018-10-02 03:35:40 +08:00
|
|
|
|
2020-05-30 07:26:30 +08:00
|
|
|
bool flag = solve(0, 0, 1, sol, xmov, ymov);
|
|
|
|
if (flag == false)
|
|
|
|
cout << "solution doesnot exist \n";
|
2018-10-02 03:35:40 +08:00
|
|
|
else
|
|
|
|
{
|
2020-05-30 07:26:30 +08:00
|
|
|
for (i = 0; i < n; i++)
|
2018-10-02 03:35:40 +08:00
|
|
|
{
|
2020-05-30 07:26:30 +08:00
|
|
|
for (j = 0; j < n; j++) cout << sol[i][j] << " ";
|
|
|
|
cout << "\n";
|
2018-10-02 03:35:40 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|