I'm working on the Knight's Tour problem and I'm making a recursive solution for it. https://www.chess.com/terms/knights-tour-chess#:~:text=The%20knight's%20tour%20is%20a,same%20square%20more%20than%20once.
I have a matrix[8][8] and a method called knightMove(int currentRow, int currentColumn);
. This method should add all possible moves that the knight can make from the current position into an array. If the value of the position of the possible move is equal to 0, then knightMove(newRow, newColumn)
will be called again from the new position.
If it finds a dead end, then it will try the next possible move in the array in the previous call. If it runs out of previous array positions, it will try the next position in the array called before this one and so on. The program will only end when it finds the right solution to the problem.
Now comes my question, I'd like to avoid use so many 'ifs' to check whether a knight move goes out of table or not.
ArrayList <int[]> moves = new ArrayList<int[]>();
int[] arr = new int[2];
int max=8;
if (currentColumn-2 > 0){
if(currentRow - 1 > 0){
arr[0] = currentColumn-2;
arr[1] = currentRow-1;
moves.add(arr);
}
if(currentRow+1 < max){
arr[0] = currentColumn-2;
arr[1] = currentRow+1;
moves.add(arr);
}
}
if (currentRow-2 > 0){
if(currentColumn-1 > 0){
arr[0] = currentColumn-1;
arr[1] = currentRow-2;
moves.add(arr);
}
if(currentColumn+1 < max){
arr[0] = currentColumn+1;
arr[1] = currentRow-2;
moves.add(arr);
}
}
if (currentColumn+2 > 0){
if(currentRow-1 > 0){
arr[0] = currentColumn+2;
arr[1] = currentRow-1;
moves.add(arr);
}
if(currentRow+1 < max){
arr[0] = currentColumn+2;
arr[1] = currentRow+1;
moves.add(arr);
}
}
if (currentRow+2 > 0){
if(currentColumn-1 > 0){
arr[0] = currentColumn-1;
arr[1] = currentRow+2;
moves.add(arr);
}
if(currentRow+1 < max){
arr[0] = currentColumn+2;
arr[1] = currentRow+1;
moves.add(arr);
}
}
for (int[] c : moves){
// recursive logic...
}
I'm not interested in invalid positions. If the compiler can't access such invalid positions, it should just don't do anything with them, and not break my code. Focus on the ones that are really a valid position. I'd like do something like below, adding just the values of valid positions in an array (Utopic solution):
int[] temp = {
table[currentRow-2][currentColumn-1],
table[currentRow-2][currentColumn+1],
table[currentRow+1][currentColumn-2],
table[currentRow-1][currentColumn-2],
table[currentRow+2][currentColumn-1],
table[currentRow+2][currentColumn+1],
table[currentRow-1][currentColumn+2],
table[currentRow+1][currentColumn+2]
};
I want help to figure out a better approach to avoid accessing an invalid position in a matrix.