附录:代码
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<memory.h>
#include<vector>
#include<algorithm>
using namespace std;
typedef struct posi
{
int x;
int y;
int selection;
posi(){};
posi(int a,int b){x=a,y=b,selection=0;}
}pos;
bool visit[9][9];
int dir_x[] = {-1, -1, -2, -2, 1, 1, 2, 2};
int dir_y[] = {-2, 2, 1, -1, 2, -2, 1, -1};
int path[64];
bool isValid(pos p)
{
if( p.x<0 || p.x>7 || p.y<0 || p.y>7 || visit[p.x][p.y]==1)
return false;
return true;
}
bool cmp(pos a,pos b)
{
return (a.selection<b.selection);
}
bool dfs(pos now,int step)
{
int i,j;
pos p(0,0);
if( step==64){
for(i=0; i<63; i++)
cout<<path[i]<<" ";
cout<<path[63]<<endl;
return true;
}
vector<pos> temp;
for(i=0; i<8; i++)
{
p.x=(now.x)+dir_x[i];
p.y=(now.y)+dir_y[i];
p.selection=0;
if(isValid(p))
{
pos k;
for( j=0; j<8; j++)
{
k.x=(p.x)+dir_x[j];
k.y=(p.y)+dir_y[j];
if( isValid(k))
p.selection++;
}
temp.push_back(p);
}
}
sort(temp.begin(),temp.end(),cmp);
for( i=0; i<temp.size(); i++){
p=temp[i];
visit[p.x][p.y]=1;
path[step]=p.x*8+p.y+1;
if(dfs( p,step+1))
return true;
visit[p.x][p.y]=0;
}
return false;
}
int main()
{
int start,row,col;
while(cin>>start && start!=-1)
{
memset(visit,0,sizeof(visit));
row=(start-1)/8;
col=(start-1)%8;
visit[row][col]=1;
path[0]=start;
dfs(pos(row,col),1);
}
return 0;
}