2008年11月30日 星期日

Knight's Tour using recursive programing


/* 若是用遞迴,對於棋盤格數較多則時間會花很久 ( 注意並非無限迴圈 ) */


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define col_size 5
#define row_size 5

void clear();
int knight(int,int);

int checker[row_size+4][col_size+4];
int step=0;
int ans=0;
// Knight's directions in X-axis and Y-axis.
const int horizontal[8]={ 2, 1,-1,-2,-2,-1, 1, 2};
const int vertical[8]={-1,-2,-2,-1, 1, 2, 2, 1}; 

int main()
{
time_t ticks1,ticks2;
int i,j,p,t;
clear();

ticks1 = time(NULL);

for(p=2;p<row_size+2;p++)
for(t=2;t<col_size+2;t++)
if(knight(p,t)==row_size*col_size)
{
printf("\nAns : %d\tStep : %d\n",++ans,step);
for(i=2;i<row_size+2;i++)
{
for(j=2;j<col_size+2;j++)
printf("%3d",checker[i][j]);
printf("\n");
}
clear();
}

ticks2 = time(NULL);

printf("\nStart time : %.24s\r\n",ctime(&ticks1));
printf(" End time : %.24s\r\n",ctime(&ticks2));

system("PAUSE");
return 0;
}

// To avoid that the knight goes out of range.
void clear()
{
int i,j;
for(i=0;i<row_size+4;i++)
for(j=0;j<col_size+4;j++)
if(i<2||i>row_size+1||j<2||j>col_size+1)
checker[i][j]=-1;
else
checker[i][j]=0;
step=0;
}

// Find the path.
int knight(int i,int j)
{
 // Set the step right now.
checker[i][j]=++step;

int p;

 // If the checker board is not full then find the next step.
if(step<row_size*col_size)
for(p=0;p<8;p++)
// Test the eight directions.
if(checker[i+vertical[p]][j+horizontal[p]]==0)
knight(i+vertical[p],j+horizontal[p]);

 // If the checker board is full then return,
 // otherwise clear the last step and restart from last step.
if(step==col_size*row_size)
return step;
--step;
checker[i][j]=0;

return step;
}

沒有留言: