1. Member
Join Date
Aug 2011
Posts
1
Rep Power
0

So, my homework is to code a program to simulate a Knight's Tour. It needs to pass all 64 spaces on an 8x8 grid, without passing the same space twice.

but my program seems to not want to pass the 29th move. I've checked everything, but I can't manage to find out where I'm wrong.
Maybe someone could assist me in finding where the problem lies.

Much appreciated!

Java Code:
public class KnightsTour
{
int grid[][];
boolean finished;
final int Xcord[] = {-1, 1, -1, 1, -2, 2, -2, 2};
final int Ycord[] = {-2, 2, 2, -2, -1, 1, 1, -1};

public static void main(String args[])
{
int totalMoves = 1;
KnightsTour kt = new KnightsTour();
kt.check( 0, 0, totalMoves);
kt.drawGrid();
}

public KnightsTour()
{
grid = new int[8][8];
finished = false;
grid[0][0] = 1;
}

public int check(int x, int y, int totalMoves)
{
for(int i = 0; i < grid.length; i++)
{
if(finished == true)
{
}
else
{
if(x+Xcord[i]<8 && x+Xcord[i]>=0)
{
if(y+Ycord[i]<8 && y+Ycord[i]>=0)
{
if((grid[x+Xcord[i]][y+Ycord[i]])==0)
{
grid[x+Xcord[i]][y+Ycord[i]]=-1;
grid[x+Xcord[i]][y+Ycord[i]]=check(x+Xcord[i],y+Ycord[i], totalMoves + 1);
finished = true;
}
}
}
}
}
if(totalMoves >= 64 || finished == true)
{
finished = true;
}
else
{
return 0;
}
}

public void drawGrid()
{
for(int i = 0; i < grid.length; i++)
{
System.out.println();
for(int j = 0; j < grid.length; j++)
{
if(grid[j][i] < 10)
{
System.out.print(" 0" + grid[j][i]);
}
else
{
System.out.print(" " + grid[j][i]);
}
}
}
}

}

2. Have you tried debugging the code by adding printlns to show the reason why it stops searching before the end?
What values of what variables stops the search?

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•