I've tried writing a code for knight's tour problem using backtracking. My code is working for 4x4 matrix, but for 8x8 matrix it is not displaying anything on the output screen.
I don't know what am I doing wrong.
This is how my code works:
If all squares are visited
print the solution
else
Add one of the next moves to solution vector and recursively check if this move leads to a solution. (A Knight can make maximum eight moves. We choose one of the 8 moves in this step).
If the move chosen in the above step doesn't lead to a solution then remove this move from the solution vector and try other alternative moves.
If none of the alternatives work then return false (Returning false will remove the previously added item in recursion and if false is returned by the initial call of recursion then "no solution exists")
Here is the code that I wrote:
#include<iostream>
using namespace std;
#define n 8
int safe(int c[n][n],int i, int j)
{
if((i>=0&&i<n)&&(j>=0&&j<n))
{
if(c[i][j])
return 0;
else
return 1;
}
return 0;
}
int knightstour(int c[n][n],int i,int j,int k)
{
if(k==n*n)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
cout<<c[i][j]<<" ";
cout<<endl;
}
return 1;
}
else
{
c[i][j]=k;
if(safe(c,i+2,j+1))
{
if(knightstour(c,i+2,j+1,k+1))
return 1;
}
if(safe(c,i+2,j-1))
{
if(knightstour(c,i+2,j-1,k+1))
return 1;
}
if(safe(c,i-2,j+1))
{
if(knightstour(c,i-2,j+1,k+1))
return 1;
}
if(safe(c,i-2,j-1))
{
if(knightstour(c,i-2,j-1,k+1))
return 1;
}
if(safe(c,i+1,j+2))
{
if(knightstour(c,i+1,j+2,k+1))
return 1;
}
if(safe(c,i-1,j+2))
{
if(knightstour(c,i-1,j+2,k+1))
return 1;
}
if(safe(c,i+1,j-2))
{
if(knightstour(c,i+1,j-2,k+1))
return 1;
}
if(safe(c,i-1,j-2))
{
if(knightstour(c,i-1,j-2,k+1))
return 1;
}
c[i][j]=0;
return 0;
}
}
int main()
{
int c[n][n]={0};
if(!knightstour(c,0,0,0))
cout<<"solution doesn't exist";
return 1;
}