#include <iostream.h>
struct point
{
int x,y;//马的位置
int dir;//这一次马行走的方向
};
struct stack
{
point p[64];//存储马的位置,方便回溯
};
int board [8][8];
int Htry1[8]={-2,-1,1,2,2,1,-1,-2};
int Htry2[8]={1,2,2,1,-1,-2,-2,-1};
bool chech[8][8]={0};//标记位置是否已经被占用
int main()
{
int i,j;
int top=0;
int z;
cout<<"请输入马的初始位置";
cin>>i;
cin>>j;
stack sta;
sta.p[top].x=i;
sta.p[top].y=j;
board [i][j]=top;
chech [i][j]=true;
int nx;
int ny;
for(int u=0;u<64;u++)
sta.p[u].dir=0;//把每个结点的dir清零
for(z=0;;)
{
if(sta.p[top].x+Htry1[z]>=0&&sta.p[top].x+Htry1[z]<8&&
sta.p[top].y+Htry2[z]>=0&&sta.p[top].y+Htry2[z]<8&&
!chech [sta.p[top].x+Htry1[z]][sta.p[top].y+Htry2[z]]//检查要走的下个位置是否可行
)
{
nx=sta.p[top].x+Htry1[z];
ny=sta.p[top].y+Htry2[z];
sta.p[top].dir=z;
top++;
sta.p[top].x=nx;
sta.p[top].y=ny;
board [nx][ny]=top;
chech [nx][ny]=true;
z=-1;
}
else if(z==7)//如果不可行,而且是最好一次检查
{ chech [sta.p[top].x][sta.p[top].y]=false;
top--;
while(1)
{
z=sta.p[top].dir;
if(z!=7)
break;
else
{ chech [sta.p[top].x][sta.p[top].y]=false;
top--;
}
}
}
if(top==-1||top==63)break;//如果回溯到-1,或者栈满,则退出循环
z++;
}
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
cout<<board [i][j]<<"";
cout<<endl;
}
return 1;
}