My chess knight tour code using recursive-backtracking is not working.
#include <iostream>
using namespace std;
// goal: knight tour
#define N 8
void printArray(int board[N][N])
{
for(int i = 0; i < N; i ++)
{
for(int j = 0; j < N; j ++)
{
cout << board[i][j] << " ";
}
cout << endl;
}
}
void instArray(int board[N][N])
{
for(int i = 0; i < N; i ++)
for(int j = 0; j < N; j ++)
board[i][j] = 0;
board[0][0] = 1;
}
bool isValidMove(int posX, int posY, int moveX, int moveY, int board[N][N])
{
int finalX = posX + moveX;
int finalY = posY + moveY;
if(finalX < 0 ||
finalX > 7 ||
finalY < 0 ||
finalY > 7 ||
board[finalY][finalX] != 0)
return false;
return true;
}
bool solveKnightTour(int board[N][N], int n, int posX, int posY, int
moveX[N], int moveY[N])
{
int next_x, next_y;
if(n == 65) return true;//when n is equal to 62 the code compiles
for(int i = 0; i < 8; i ++)
{
if(isValidMove(posX, posY, moveX[i], moveY[i], board))
{
next_x = posX + moveX[i];
next_y = posY + moveY[i];
board[next_y][next_x] = n;
if(solveKnightTour(board, n + 1, next_x, next_y, moveX, moveY))
return true;
else board[next_y][next_x] = 0;
}
}
return false;
}
int main()
{
int board[N][N];
int moveX[8] = {1, 1, 2, 2, -1, -1, -2, -2};
int moveY[8] = {2, -2, 1, -1, 2, -2, 1, -1};
instArray(board);
solveKnightTour(board, 2, 0, 0, moveX, moveY);
printArray(board);
}
There is no error, but the code seems to endlessly loop. In solveKnightTour function, when n is equal to 62, the code compiles with printed board, but the result is not a completely solved knight tour.