Hello Guys I am trying to learn Backtracking and so I tried solving the famous Knight Tour problem. I have written the code but I dont know where its going wrong. Output Expected: The 2d array with numbers printed from 0 to 63. Output Im getting : Soln doesnt exist
Pls Help.
#include<bits/stdc++.h>
using namespace std;
#define N 8
bool knightTour(int arr[N][N],int movei, int dx[],int dy[],int i,int j)
{
if(movei == N*N)
return true;
int next_x,next_y;
for(int k=0;k< 8;k++)
{
next_x = i + dx[k];
next_y = j + dy[k];
if(next_x >= 0 && next_x < N && next_y>=0 && next_y < N && arr[next_x][next_y]==-1)
{
arr[next_x][next_y] = movei;
if(knightTour(arr,movei+1,dx,dy,next_x,next_y))
return true;
else
arr[next_x][next_y] = -1;
}
}
return false;
}
int main()
{
int arr[N][N] ={-1};
int dx[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int dy[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
arr[0][0] = 0; // Since the knight starts from 0,0
if(knightTour(arr,1,dx,dy,0,0) == true)
{
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}
else
{
cout<<"No soln Exists";
}
}