1. Member
Join Date
Feb 2008
Posts
3
Rep Power
0

## Knights Tour.

Hello all, Im having a bit of trouble with a project.

I need to create a program that finds a solution to the knights tour problem (a chess Knight must travel to each space on a chess board, but can only enter each space once.)

The code I wrote seems to work when i make the base case 63 (but one square is unreached), when the base case is 64 it seems to loop forever. Anyhelp would surely be appreciated.

Java Code:
```public class Main {

public static void main(String args[])
{
int count = 1;
Tour knightsTour = new Tour();
knightsTour.check( 0, 0, count);
knightsTour.printBoard();

}

}```
Java Code:
```public class Tour {
int board[][];
boolean done;
final int xaval[] = {-1, 1, -1, 1, -2, 2, -2, 2};
final int yaval[] = {-2, 2, 2, -2, -1, 1, 1, -1};

public Tour()
{
board=new int[8][8];
done = false;
board[0][0]=1;
}

public int check(int x, int y, int count)
{
for(int i = 0; i < 8; i++)
{
if(done == true)
{
return count;
}
else
{
if(x+xaval[i]<8 && x+xaval[i]>=0)
{
if(y+yaval[i]<8 && y+yaval[i]>=0)
{
//on the board
if((board[x+xaval[i]][y+yaval[i]])==0)
{
board[x+xaval[i]][y+yaval[i]]=-1;
board[x+xaval[i]][y+yaval[i]]=check(x+xaval[i],y+yaval[i], count + 1);
}
}

}
}

}
if(count >= 64 || done == true)
{
done = true;
return count;
}
else
{
return 0;
}

}

public void printBoard()
{

//Draw Board
for(int i = 0; i < 8; i++)
{
System.out.println("\n________________________");
for(int j = 0; j < 8; j++)
{
if(board[j][i] < 10)
{
System.out.print("|0" + board[j][i]);
}
else
{
System.out.print("|" + board[j][i]);
}
}
}
}

}```

2. Member
Join Date
Feb 2008
Posts
3
Rep Power
0

Thanks.

#### Posting Permissions

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