I'm trying to implement the knight's tour recursively.. below is my code. I chose the board to be 5x5 for simplicity. My goal is to print out the correct knight placements and possibly show backtracking at the same time with print statements.
class Knight
{
public boolean[][] board = new boolean[5][5];
public final int SQUARES = 5*5-1;
public Knight()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
board[i][j] = false;
}
public boolean tour(int x, int y, int visitedX, int visitedY,int n)// x,y coords, just visited x,y and counter n
{
if(x>=5||y>=5||x<0||y<0){ //out of bounds
System.out.println("Visited "+x+", "+y+" Out of bounds");
System.out.println("Back to "+visitedX+", "+visitedY);
return false;
}
else{
if(board[x][y] == true)
{return false;}
if(board[x][y]!=true){
boolean result = false;
board[x][y]=true;
System.out.println("Visited "+x+", "+y);
result = tour(x+2,y+1,x,y,n+1);
result = tour(x+2,y-1,x,y,n+1);
result = tour(x+1,y-2,x,y,n+1);
result = tour(x-1,y-2,x,y,n+1);
result = tour(x+1,y+2,x,y,n+1);
result = tour(x-1,y+2,x,y,n+1);
result = tour(x-2,y-1,x,y,n+1);
result = tour(x-2,y+1,x,y,n+1);
}
}
return false;
}
}
public class KnightTApp {
public static void main(String[] args) {
Knight k = new Knight();
k.tour(0,0,0,0,0);
}
}
part of print output
Visited 4, 0
Visited 6, 1 Out of bounds
Back to 4, 0
Visited 6, -1 Out of bounds
Back to 4, 0
Visited 5, -2 Out of bounds
Back to 4, 0
Visited 3, -2 Out of bounds
Back to 4, 0
Visited 5, 2 Out of bounds
Back to 4, 0
Visited 2, -1 Out of bounds
Back to 4, 0
Visited 2, 0
My problem is in the middle of the process, I run into a dead end situation(where not all squares are covered yet there are no legal moves I can make) at index 4,0. And Since I have not included any lines for backtracking. It just jumps to index 2,0 which is not even a legal knight move.
My question is how do I express a Dead end situation with an if statement? I think I should set the recursion to some kind of boolean and go from there but I have no idea how to do it.
And also is using recursion same as using DFS(depth first search) because they basically have the same idea?
Thank you in advance.
false
fromtour()
you have no way of signalling success/failure back up the call tree. you only ever say "failed". – Marc B