I wrote this code to print one of the possible knight's tour such that every place is visited exactly once.
public class Main{
static int move[][]=new int[8][8];
static int X[]={1 , 2 , 2 , 1 ,-1 ,-2 ,-2,-1};
static int Y[]={2 , 1 ,-1 ,-2 ,-2 ,-1 , 1, 2};
static boolean printMove(int x,int y,int step){
if(step==65){
return true;
}
else{
int x1,y1;
for(int l=0;l<8;l++){
x1=x+X[l];
y1=y+Y[l];
if(x1<8&&y1<8&&x1>=0&&y1>=0&&move[x1][y1]==0){
move[x1][y1]=step;
if(printMove(x1,y1,step+1)){
return true;
}
else
move[x1][y1]=0;
}
}
return false;
}
}
static void printSteps(){
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
System.out.print(move[i][j]+" ");
}
System.out.println();
}
}
public static void main(String args[]){
move[0][0]=1;
printMove(0,0,2);
printSteps();
}
}
this code is working but the following code is not working, I made little change in X[] and Y[] which should not effect the algorithm.
public class Main{
static int move[][]=new int[8][8];
static int X[]={-1, 1 , 2 , 2 , 1 ,-1 ,-2 ,-2};
static int Y[]={ 2, 2 , 1 ,-1 ,-2 ,-2 ,-1 , 1};
static boolean printMove(int x,int y,int step){
if(step==65){
return true;
}
else{
int x1,y1;
for(int l=0;l<8;l++){
x1=x+X[l];
y1=y+Y[l];
if(x1<8&&y1<8&&x1>=0&&y1>=0&&move[x1][y1]==0){
move[x1][y1]=step;
if(printMove(x1,y1,step+1)){
return true;
}
else
move[x1][y1]=0;
}
}
return false;
}
}
static void printSteps(){
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
System.out.print(move[i][j]+" ");
}
System.out.println();
}
}
public static void main(String args[]){
move[0][0]=1;
printMove(0,0,2);
printSteps();
}
}
I just changed
static int X[]={1 , 2 , 2 , 1 ,-1 ,-2 ,-2,-1};
static int Y[]={2 , 1 ,-1 ,-2 ,-2 ,-1 , 1, 2};
to
static int X[]={-1, 1 , 2 , 2 , 1 ,-1 ,-2 ,-2};
static int Y[]={ 2, 2 , 1 ,-1 ,-2 ,-2 ,-1 , 1};