I am trying to solve the problem where the problem states that, given a N * M chessboard, a Knight’s Tour is defined as the sequence of moves of a Knight, such that the Knight visits every square only once. Below is my code, however I am getting Array out of bound = 8, I know it comes when Moves tries to add value 2 in the present row with 6, however I am not sure how to get rid of it.
int MaxMove = 64; // for 8*8 chess Board
private int Moves[][] = new int[][] {{2, 1}, {2, -1}, {1, 2}, {1, -2}, {-2, 1}, {-2, -1}, {-1, 2}, {-1, -2}};
void solveKnightTour(int[][] board)
{
knightsTourUtil(board, 0, 0, 1);
}
private boolean isSafeMove(int[][] board, int r, int c)
{
if(r < 0 && r > board.length-1 && c < 0 && c > board.length-1 && board[r][c] != -1)
return false;
return true;
}
private boolean knightsTourUtil(int[][] board, int presentRow, int presentCol, int KthMove)
{
if (KthMove >= MaxMove)
{
return true;
}
for (int i = 0; i < Moves.length; i++)
{
int nextRow = presentRow + Moves[i][0];
int nextCol = presentCol + Moves[i][1];
if (isSafeMove(board, nextRow, nextCol))
{
board[nextRow][nextCol] = KthMove;
if (knightsTourUtil(board, nextRow, nextCol, KthMove + 1))
return true;
else
board[nextRow][nextCol] = -1;
}
}
return false;
}