轉載一個快速的騎士周遊程式

lt發表於2016-11-08

來自這裡

#include"stdio.h"
#include"conio.h"
#define N 8    /*How many the horse最好不要超過19(超出螢幕)*/

int top=0;

struct stack
{       int x;
 int y;
 int step;
}ma[N*N+1]={{0,0,0}};

void push(int a[][N],int i,int j,int m)
{   ma[top].x=i;
 ma[top].y=j;
 ma[top].step=m;
 a[i][j]=++top;
}

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 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;
}
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 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 disp(int a[][N])
{       int i,j;
 for(i=0;i<N;i++){
     for(j=0;j<N;j++)
  printf("%4d",a[i][j]);
     printf("\n");
 }
}

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);
}

int 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;
}

8*8棋盤輸入1,2,立刻出結果
作為比較 http://blog.csdn.net/jiajiayouba/article/details/9293379 6*6棋盤要60秒算出一個結果 https://software.intel.com/protected-download/145170/249799 5*6棋盤序列要29秒算出10個結果

相關文章