*骑士周游,编号优先法*/
#include<stdio.h>
#include<time.h>
int a[8][8];
int temp;
int currentrow,currentcol;
int horizontal[8]={2,1,-1,-2,-2,-1,1,2};
int vertical[8]={-1,-2,-2,-1,1,2,2,1};
int b[8][8]={ {2,3,4,4,4,4,3,2},
{3,4,6,6,6,6,6,3},
{4,6,8,8,8,8,6,4},
{4,6,8,8,8,8,6,4},
{4,6,8,8,8,8,6,4},
{3,4,6,6,6,6,4,3},
{2,3,4,4,4,4,3,2} };
int ISOK(int n); //判断是否64步成功走完
int possible(); //试探走步
int output();
int possible_sort(); //找出最高优先的一种方法
void main()
{
int i,j,isok=0,rand_num1,rand_num2;
srand((unsigned)time(NULL));
j=1;
rand_num1=1; /*起始行*/
rand_num2=3; /*起始列*/
while(isok==0)
{
i=possible();
if(i<=7)
{
j++;
a[currentrow][currentcol]=j;
}
if(i>7) //不成功。及初始化
{
isok=ISOK(j);
if(isok==0)
{
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{ a[i][j]=0;}
}
currentrow=rand_num1;
currentcol=rand_num2;
j=1;
a[currentrow][currentcol]=j;
}
}
}
output();
}
int possible(void)
{
int possible_num,i,j,n;
possible_num=0;
while(possible_num<=7)
{
possible_num=rand()%8;
i=currentrow;
j=currentcol;
i+=vertical[possible_num];
j+=horizontal[possible_num];
n=possible_sort();
if(n>7)
{ return n;}
if(b[i][j]>temp) //判断随机值是否有最高优先级
{ possible_num=n; }
if(i>=0&&i<=7&&j>=0&&j<=7&&a[i][j]==0)
{
i=currentrow;
j=currentcol;
i+=vertical[possible_num];
j+=horizontal[possible_num];
currentrow=i;currentcol=j;
return possible_num;
}
}
}
int ISOK(int n)
{
int i;
if(n==64)
{ i=1;return i;}
else return i=0;
}
int output(void)
{
int i,j;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
}
int possible_sort()
{
int i,j,possible_num,possible_min,END;
temp=8;
for(possible_num=0,END=0;possible_num<=7;possible_num++)
{
i=currentrow;
j=currentcol;
i+=vertical[possible_num];
j+=horizontal[possible_num];
if(i>=0&&i<=7&&j>=0&&j<=7&&a[i][j]==0)
{
if(b[i][j]<=temp)
{ temp=b[i][j];
possible_min=possible_num;
}
}
else END++;
}
if(END>7)
{ return END;}
return possible_min;
}
转载于:https://blog.51cto.com/6988130/1195669