I have made a program to the follwoing problem:-
Another chessboard puzzle (this one reputedly solved by GAUSS at the age of four) is to find a sequence of moves by a knight that will visit every square of the board exactly once. Write a backtracking program that will input an initial position and search for a knight’s tour starting at the given position and going to every square once and no square more than once.
The program is:-
#include<iostream>
using namespace std;
int max_size=10;
int count1=1;
class knight
{
public:
knight(int);
int size;
int arr[10][10];
void mark(int &);
void unmark(int &);
void print();
void mf(int, int);
bool unvisited(const int&);
};
knight::knight(int a)
{
int i,j;
size=a;
for(i=0;i<=a-1;i++)
for(j=0;j<=a-1;j++)
arr[i][j]=0;
}
void knight::mark(int &a)
{
a=count1;
count1++;
}
void knight::unmark(int &a)
{
a=0;
count1--;
}
void knight::print()
{
for(int i=0;i<=size-1;i++)
for(int j=0;j<=size-1;j++)
cout<<"\nKnight went to the "<<i<<','<<j<<" block in "<<arr[i][j]<<"th turn!";
}
void knight::mf(int x, int y)
{
if(count1==((size*size)+1))
print();
else if(unvisited(arr[x][y])&&(x+2<=(size-1))&&(y+1<=(size-1)))
{
mark(arr[x][y]);
mf(x+2,y+1);
unmark(arr[x][y]);
}
else if(unvisited(arr[x][y])&&(x+1<=(size-1))&&(y+2<=(size-1)))
{
mark(arr[x][y]);
mf(x+1,y+2);
unmark(arr[x][y]);
}
else if(unvisited(arr[x][y])&&(x+2<=(size-1))&&(y-1>=0))
{
mark(arr[x][y]);
mf(x+2,y-1);
unmark(arr[x][y]);
}
else if(unvisited(arr[x][y])&&(x+1<=(size-1))&&(y-2>=0))
{
mark(arr[x][y]);
mf(x+1,y-2);
unmark(arr[x][y]);
}
else if(unvisited(arr[x][y])&&(x-2>=0)&&(y+1<=(size-1)))
{
mark(arr[x][y]);
mf(x-2,y+1);
unmark(arr[x][y]);
}
else if(unvisited(arr[x][y])&&(x-1>=0)&&(y+2<=(size-1)))
{
mark(arr[x][y]);
mf(x-1,y+2);
unmark(arr[x][y]);
}
else if(unvisited(arr[x][y])&&(x-2>=0)&&(y-1>=0))
{
mark(arr[x][y]);
mf(x-2,y-1);
unmark(arr[x][y]);
}
else if(unvisited(arr[x][y])&&(x-1>=0)&&(y-2>=0))
{
mark(arr[x][y]);
mf(x-1,y-2);
unmark(arr[x][y]);
}
}
bool knight::unvisited(const int& a)
{
if(a==0)
return 1;
else return 0;
}
int main()
{
knight example(3);
example.mf(0,0);
}
When, I run this program, nothing happens. Nothing is displayed.
Whats wrong with the program?