WA了很多次。
#include <stdio.h>
#include <string.h>
#define MAX 30
bool visit[MAX][MAX], tag;
int dir[8][2] = { {-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1} };
int n, p, q;
char path[MAX][2];
bool is_leagal(int x, int y)
{
if (x < 1 || x > q || y < 1 || y > p)
return false;
if (visit[x][y])
return false;
return true;
}
void dfs(int x, int y, int step)
{
if (step == p * q) {
tag = true;
return;
}
int temp_x, temp_y;
for(int i = 0; i < 8; ++i) {
temp_x = x + dir[i][0];
temp_y = y + dir[i][1];
if (is_leagal(temp_x, temp_y))
{
path[step][0] = temp_x + 'A' - 1;
path[step][1] = temp_y + '0';
visit[temp_x][temp_y] = true;
dfs(temp_x, temp_y, step + 1);
if (tag) return;
visit[temp_x][temp_y] = false;
}
}
}
int main()
{
while (scanf("%d", &n) != EOF) {
for(int i = 0; i < n; ++i) {
scanf("%d%d", &p, &q);
memset(path, 0, sizeof(path));
memset(visit, false, sizeof(visit));
tag = false;
visit[1][1] = 1;
path[0][0] = 'A';
path[0][1] = '1';
printf("Scenario #%d:\n", i + 1);
dfs(1, 1, 1);
if (tag) {
for(int j = 0; j < p * q; ++j)
printf("%c%c", path[j][0], path[j][1]);
}
else
printf("impossible");
printf("\n\n");
}
}
}
1,结尾一个换行两个换行都可以过。
2,y是q,是字母,x是p,是数字
3,字典序,从小到大。
DFS的基础题,WA了很多次。