So I have to write this algorithm (this version does not need to end in the same spot that knight started), and I got it to work, but it's too slow. It works with starting positions x=0 and y=0 for size=8, but if I try to manipulate x and y to for example 2 and 4 it doesn't end after a few minutes. Can anyone help?
#include <stdio.h>
#define size 8
int ruch_x[]={ -1, 1, -2, 2, -2, 2, -1, 1}; //arrays of possible knight moves, for example 2nd move is [1,2]//
int ruch_y[]={ 2, 2, 1, 1, -1, -1, -2, -2};
int done(int szach[][size])
{
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
if(szach[i][j]==0)
return 0;
}
}
return 1;
}
//licz - variable for counting knights moves//
void konik(int szach[][size], int x, int y, int licz)
{
szach[x][y]=licz;
if(licz<size*size){
for(int i=0;i<=7;i++){ //loop that checks every possible knight move//
if(szach[x+ruch_x[i]][y+ruch_y[i]]==0&&x+ruch_x[i]>=0&&x+ruch_x[i]<size&&y+ruch_y[i]>=0&&y+ruch_y[i]<size)
// checking if candidat was already visited and if it's not outside of the board//
{
konik(szach, x+ruch_x[i], y+ruch_y[i], licz+1);}}}
if(done(szach)==1) return; //checking if whole board is filled with numbers, if yes then skip zeroing current move//
szach[x][y]=0;
}
int main()
{
int i, j, x,y;
printf("set x\n");
scanf("%d", &x);
printf("set y\n");
scanf("%d", &y);
int szach[size][size];
for(i=0;i<size;i++) { //zeroing array//
for(j=0;j<size; j++) {
szach[i][j]=0; }}
konik(szach, x, y, 1);
for(int i=0;i<size;i++) {
for(int j=0;j<size; j++) {
printf("%d\t",szach[j][i]); }
printf("\n\n");}
printf("\n");
return 0;
}
This is by no means an answer, just an idea that might be helpful.
I remember that for some sizes a simple spiral pattern will fill the outer edge of the board and reduce the problem to a simpler one with
size
smaller by 4.You can use this idea to simplify your problem. For example, fill a 8x3 and a 8x5 board instead of a 8x8 board (you will have to update your algorithm to look for suitable ending position).