控制好八个方向就行,安字典序,所以~~~先列再行
代码
#include <algorithm>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
int step;
int flag;
int path[50][50];
int book[50][50];
int dx[] = {-1,1,-2,2,-2,2,-1,1};
int dy[] = {-2,-2,-1,-1,1,1,2,2};
int n, m;
void DFS(int x, int y, int s)
{
path[s][0] = x;
path[s][1] = y;
if(s == step){
flag = true;
return;
}
for(int i = 0;i < 8;i++){
int xx = x + dx[i];
int yy = y + dy[i];
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&!book[xx][yy]&&!flag){
book[xx][yy] = 1;
DFS(xx,yy,s+1);
book[xx][yy] = 0;
}
}
}
int main()
{
int t;
scanf("%d", &t);
int cnt = 0;
while(t--){
flag = false;
cnt++;
scanf("%d %d", &n, &m);
step = n*m;
printf("Scenario #%d:\n", cnt);
memset(book,0,sizeof(book));
book[1][1] = 1;
DFS(1,1,1);
if(flag){
for(int i = 1;i <= step;i++){
printf("%c%d", path[i][1]-1+'A',path[i][0]);
}
printf("\n");
}else {
printf("impossible\n");
}
printf("\n");
}
return 0;
}