int pop(int a[][N])
{ int temp;
top--;
a[ma[top].x][ma[top].y]=0;
ma[top].x=0;
ma[top].y=0;
temp=ma[top].step+1;
ma[top].step=0;
return temp;
}
int jump(int i,int j,int a[][8])
{ int col[]={2,1,-1,-2,-2,-1,1,2};
int row[]={-1,-2,-2,-1,1,2,2,1};
int t,ti=i,tj=j,count=0;
for(t=0;t<8;t++){
ti+=row[t];tj+=col[t];
if(judge(ti,tj,a))
count++; /*How many ways for the horse can jump for second time.*/
ti-=row[t];tj-=col[t];
}
return count;
}
int judge(int i,int j,int a[][N]) /*Judge the position can jump */
{ if(i>=0&&j>=0&&i<N&&j<N&&a[i][j]==0)
return 1;
return 0;
}
sort(int a[8],int b[8])
{ int i,min=a[0],t=0;
for(i=1;i<8;i++){
if(min>a[i]&&a[i]>-1&&a[i]<8){
min=a[i]; /*Find the Min-way the horse to jump*/
t=b[i];
}
}
return t;
}
void horse(int x,int y)
{ int i=x,j=y,min,ti,tj,t,temp=0,flag=0,temp1=0;
int count[8],num[8]={0};
int col[]={2,1,-1,-2,-2,-1,1,2};
int row[]={-1,-2,-2,-1,1,2,2,1};
int a[N][N]={{0}};
for(x=0;x<8;x++)
count[x]=8;
push(a,i,j,0);
while(top<N*N)
{ ti=i;tj=j;temp1=0;flag=0;
for(x=0;x<8;x++)
count[x]=8;
for(t=temp;t<8;t++,temp1++){ /*How many ways for the horse can jump for first time*/
ti+=row[t];tj+=col[t];
if(judge(ti,tj,a)){
count[temp1]=jump(ti,tj,a);
num[temp1]=t;
flag=1;
}
ti-=row[t];tj-=col[t];
}
if(flag){
min=sort(count,num);
ti+=row[min];tj+=col[min];
push(a,ti,tj,min); /*In the stack*/
i=ti;j=tj;
temp=0;
}
else{
temp=pop(a); /*Return the stack*/
i=ma[top-1].x;
j=ma[top-1].y;
}
}
printf("\n\n");
disp(a);
}
main()
{ int x,y;
do{
printf("Please enter the X-position :");
scanf("%d",&x);
printf("Please enter the Y-position :");
scanf("%d",&y);
if(x>N||y>N||x<1||y<1)
printf("Error! Try it again,X(1~%d),Y(1~%d)\n",N,N);
}while(x>N||y>N||x<1||y<1);
horse(x-1,y-1);
getch();
return 0;
}