#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
//#define DEBUG
/* 248K 0MS */
static int dx[8] = {-2, -2, -1, -1, 1, 1, 2, 2}; /* 骑士只有8个位置可以移动 */
static int dy[8] = {-1, 1, -2, 2, -2, 2, -1, 1}; // 字典序。
static int board[26][26];
static int count;
static int ok;
static int p, q;
static char path[26 * 2];
void search_dfs(int x, int y, int num)
{
if (num >= count)
{
ok = 1;
for (int i = 0; i < count * 2; i+=2)
printf("%c%c", path[i], path[i + 1]);
printf("\n");
return;
}
if (1 == ok) return;
for (int i = 0; i < 8; i++)
{
int newx = x + dx[i];
int newy = y + dy[i];
if (newx >= q || newx < 0 || newy >= p || newy < 0 || board[newx][newy] == 1) continue;
board[newx][newy] = 1;
path[num * 2] = 'A' + newx; path[num * 2 + 1] = '1' + newy;
search_dfs(newx, newy, num + 1);
board[newx][newy] = 0;
//path[num * 2] = 0; path[num * 2 + 1] = 0; /* ????*/
}
}
int main()
{
#ifdef DEBUG
fstream cin("G:\\book\\algorithms\\acm\\Debug\\dat.txt");
#endif
int t;
cin >> t;
for (int s = 1; s <= t; s++)
{
cin >> p >> q;
int i, j;
for (i = 0; i < p; i++)
for (j = 0; j < q; j++)
board[i][j] = 0;
printf("Scenario #%d:\n", s);
board[0][0] = 1; count = p * q; ok = 0;
path[0] = 'A'; path[1] = '1';
search_dfs(0, 0, 1);
if (0 == ok)
printf("impossible\n");
printf("\n");
}
return 0;
}
问题链接 POJ 2488 对于递归的过程需要认真思考。