解题报告:
1、DFS遍历,并且记录走过的路径(先数字代替),不重复地全部走完。
2、需要按照字典序输出,注意方向数组的方向顺序,并且从A1开始搜索。
3、DFS的参数用于记录状态转移量(x,y)和递归的深度(step)。
4、使用全局变量简化程序的设计。
AC代码:
#include <iostream>
#include <cstring>
#define MAXN 10
using namespace std;
int p, q, cnt, flag;
int vis[MAXN][MAXN], path[MAXN*MAXN][2];
int dir[8][2] = {{-1,-2}, {1,-2}, {-2,-1}, {2,-1}, {-2,1}, {2,1}, {-1,2}, {1,2}};
void dfs(int x, int y, int step)
{
if(step == p*q)
{
cout << "Scenario #" << ++cnt << ":" << endl;
for(int i = 0; i < p*q; i++)
cout << (char)(path[i][1]+'A') << (int)(path[i][0]+1);
cout << endl << endl;
flag = 1;
return;
}
else for(int d = 0; d < 8; d++)
{
int nx, ny;
nx = x + dir[d][0];
ny = y + dir[d][1];
if(!vis[nx][ny] && nx>=0 && nx<p && ny>=0 && ny<q)
{
vis[nx][ny] = 1;
path[step][0] = nx;
path[step][1] = ny;
dfs(nx, ny, step+1);
vis[nx][ny] = 0;
if(flag) return;
}
}
}
int main(void)
{
int t;
while(cin >> t)
{
cnt = 0;
while(t--)
{
flag = 0;
memset(vis, 0, sizeof(vis));
cin >> p >> q;
path[0][0] = 0;
path[0][1] = 0;
vis[0][0] = 1;
dfs(0, 0, 1);
if(!flag)
{
cout << "Scenario #" << ++cnt << ":" << endl;
cout << "impossible" << endl << endl;
}
}
}
return 0;
}