Why we need backtracking for The Knight’s tour problem? Can we do it by using only recursion? i have tried to do it but it give wrong answer and i am not able to figure out where code or logic goes wrong.
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int[][] ans=new int[8][8];
for(int d=0;d<8;d++){
for(int e=0;e<8;e++){
ans[d][e]=-1;
}
}
int[] x={2,1,-2,1,-1,-2,-1,2};
int[] y={1,2,1,-2,-2,-1,2,-1};
func(x,y,ans,7,7,1);
}
public static void func(int[] x,int[] y,int[][] ans,int i,int j,int count){
if(count==64){
for(int d=0;d<8;d++){
for(int e=0;e<8;e++){
System.out.print(ans[d][e]+" ");
}
System.out.println();
}
}
if(ans[i][j]!=-1){
return;
}
else{
ans[i][j]=count;
for(int u=0;u<8;u++){
if(i+x[u]>=0 && i+x[u]< 8 && j+y[u]>=0 && j+y[u]<8){
func(x,y,ans,i+x[u],j+y[u],count+1);
}
}
}
return;
}
}
The need for back-tracking in the knights tour problem is critical. The fact that you have not implemented your back-tracking in your code is the main reason why it does not work.
To fix it you must at least clear the position at the end of your method. I.e when you do
ans[i][j] = count
you must balance that with aans[i][j] = -1
to clear that square - you are not doing this.That is not the only problem with your code but it is the main one.
Alternatives to back-tracking exist. You can create a new board at ever recursion level which is a copy of the current board but that is generally considered wasteful of memory.
Here's the code I ended up with:
Be patient - it takes a long time to complete - as you would expect. On my PC it takes about 20 minutes to get to:
I made the following changes:
x
andy
arraysstatic
- they do not need to be parameters.static final
EMPTY
to indicate empty.boolean
result when finished to stop the search there.board
andknightsMove
.SIZE
for board size.Please do not use this code for your homework - you will learn much more by doing this yourself and understanding why each part works.