给定一个棋盘,看骑士能不能不重复的走完所有的格子,输出按字典序排列的第一种路径
#include <cstdio>
#include <cstring>
const int MAXN = 30;
bool flag;
int g[MAXN][MAXN];
char path[60];
int n,m,res;
//要注意这里的顺序
int dir[8][2] = {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};
void dfs(int row, int col, int cnt)
{
if(flag) return;
if(cnt == res)
{
puts(path);
flag = true;
return;
}
int tx,ty;
for(int k = 0; k < 8; ++k)
{
tx = row + dir[k][0];
ty = col + dir[k][1];
if(tx < 0 || ty < 0 || tx >= n || ty >= m) continue;
if(!g[tx][ty])
{
g[tx][ty] = 1;
path[cnt*2] = ty + 'A';
path[cnt*2+1] = tx + '1';
dfs(tx,ty,cnt+1);
g[tx][ty] = 0;
}
}
}
int main()
{
int t;
int time = 0;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&m);
flag = false;
res = n*m;
printf("Scenario #%d:\n",++time);
for(int j = 0; j < m; ++j)
{
for(int i = 0; i < n; ++i)
{
memset(g,0,sizeof(g));
memset(path,0,sizeof(path));
path[0] = j + 'A';
path[1] = i + '1';
g[i][j] = 1;
dfs(i,j,1);
if(flag) break;
}
if(flag)break;
}
if(!flag)
printf("impossible\n");
printf("\n");
}
return 0;
}