题目大意:马步行走,使其能够遍历全图,字典序输出
分析:DFS。要求字典序输出,所以,辅助数组的初始化,需从左至右初始。
代码:
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 31;
int vis[maxn][maxn], path[maxn*maxn][2];
int dx[8] = {-2, -2, -1, -1, 1, 1, 2, 2}; //辅助数组初始化时需注意顺序
int dy[8] = {-1, 1, -2, 2, -2, 2, -1, 1};
int n, m, cnt = 1, flag;
int dfs(int x, int y) {
if(cnt == n*m) {
for(int i = 1; i <= cnt; i++)
printf("%c%d", path[i][0]+'A'-1, path[i][1]);
flag = 1;
return true;
}
else {
;
for(int i = 0; i < 8; i++) {
int s = x + dx[i], t = y + dy[i];
if(!(s < 1 || s > m || t < 1 || t > n) && !vis[s][t] && !flag) {
cnt++;
vis[s][t] = 1;
path[cnt][0] = s;
path[cnt][1] = t;
dfs(s, t);
cnt--;
vis[s][t] = 0;
}
}
return false;
}
}
int main() {
int k;
scanf("%d", &k);
for(int i = 0; i < k; i++) {
scanf("%d%d", &n, &m);
memset(vis, 0, sizeof(vis));
memset(path, 0, sizeof(path));
printf("Scenario #%d:\n", i+1);
vis[1][1] = 1;
path[1][0] = 1;
path[1][1] = 1;
flag = 0;
dfs(1, 1);
if(flag) printf("\n\n");
else printf("impossible\n\n");
}
return 0;
}