题目
给你一个p*q的棋盘,跳马在上面的任意一格开始移动,只能走‘日’字,问你能不能经过棋盘上面所有的格子。输出要按照字典顺序输出
样例
样例输入
3
1 1
2 3
4 3
样例输出
Scenario #1:
A1
Scenario #2:
impossible
Scenario #3:
A1B3C1A2B4C2A3B1C3A4B2C4
AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int to[9][2] = {{0, 0}, {-1, -2}, {1, -2}, {-2, -1}, {2, -1}, {-2, 1}, {2, 1}, {-1, 2}, {1, 2}}; //代表方向。 设置数组从1开始,所printf("%c%d",a[i].y-1+'A',a[i].x);
int vis[50][50]; // 标记走过的地方
int n, m, flag;
struct loc
{
int x, y;
} a[30];
void dfs(int x, int y, int step)
{
//把当前路径存入结构体
a[step].x = x;
a[step].y = y;
if (step == n * m) //搜完每一个格子,代表产生了一个路径
{
flag = 1;
for (int i = 1; i <= step; i++)
printf("%c%d", a[i].y - 1 + 'A', a[i].x); //(cout<<a[i].y-1+'A'<<a[i].x;)
cout << endl;
}
if (flag)
return;
for (int i = 1; i <= 8; i++)
{
int xx = x + to[i][0]; // 填充x方向
int yy = y + to[i][1]; // 填充y方向
if (xx > 0 && xx <= n && yy > 0 && yy <= m && vis[xx][yy] == 0) //判断是否越界
{
vis[xx][yy] = 1; //搜过的标记
dfs(xx, yy, step + 1);
vis[xx][yy] = 0; //标记回来
}
}
}
int main()
{
int t, ci = 1;
cin >> t;
while (t--)
{
memset(vis, 0, sizeof(vis));
flag = 0;
cin >> n >> m;
cout << "Scenario #" << ci++ << ":" << endl;
vis[1][1] = 1; // b标记第一个坐标,起点
dfs(1, 1, 1); //从(1,1)开始搜索
if (flag == 0)
cout << "impossible" << endl;
cout << endl;
}
return 0;
}