深搜,不怎么会用,不过渐渐有点懂了,看了网上的代码才做出来
#include<iostream>
#include<cstring>
using namespace std;
int q[31];
int xy[8][2] = {{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1}};
bool vis[6][7],f;
void dfs(int x, int y, int p)
{
if(f) return;
else if(p==30)
{
f = 1;
for(int i = 0; i < 29; i++)
cout << q[i] << " ";
cout << q[29] << endl;
return;
}
for(int i = 0; i < 8; i++)
{
if(f) break;
int tx = x + xy[i][0], ty = y + xy[i][1];
if(tx > 0 && tx < 6 && ty > 0 && ty < 7 && !vis[tx][ty])
{
q[p] = 6*tx + ty - 6;
vis[tx][ty] = 1;
dfs(tx,ty,p+1);
vis[tx][ty] = 0;
}
}
}
int main()
{
int n;
while(cin >> n && n != -1)
{
memset(vis,0,sizeof(vis));
memset(q,0,sizeof(q));
f = 0,q[0] = n;
int x = (n-1)/6+1, y = (n-1)%6+1;
vis[x][y] = 1;
dfs(x,y,1);
}
}