题目链接
整天待在一个方块里, 骑士感到特别的无聊, 于是, 他决定来一场所走就走的旅行
但他只能走日字, 并且世界是一个不大于88的棋盘.你能帮勇敢的骑士制定一个旅行计划吗?
请找出一条路使得骑士能够走遍整个棋盘.骑士可以在任一方块出发或结束
Input
第一行输入一个正整数n, 代表数据组数
对于每组数据, 含有两个正整数p和q(1 <= pq <= 26), 表示一个p*q的棋盘.每个方块的位置用两个字符表示, 第一个从A开始,代表列, 第二个从1开始,代表行
Output
每组数据的结果首先是一行"Scenario #i:", i是数据序号, 从1开始
然后输出一行, 是字典序第一的可以走遍棋盘的路径, 接着有一个空行
路径应该是连续的依次所走方块的位置
如果不存在这样的路径, 输出"impossible"
Sample Input
3
1 1
2 3
4 3
Sample Output
Scenario #1:
A1
Scenario #2:
impossible
Scenario #3:
A1B3C1A2B4C2A3B1C3A4B2C4
题目描述
其实只能行走到图中的白圈,可以从任意位置开始,要求骑士走完地图并输出行走的字典序最小的路径
思路:对骑士所能走的8个方向进行搜索,要求字典序最小,那么就要从A1开始,要求输出路径,就需要开一个数组存储路径
代码如下
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
//骑士行走的方向
int next[8][2] = {
{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}
};
//flag标记骑士是否走完,book记录图中行走情况
int flag,p,q,book[30][30];
//记录骑士走过的路径
struct node
{
int x,y;
}ans[30];
void dfs(int x, int y, int step)
{
int i,tx,ty;
//记录每次行走的坐标
ans[step].x = x;
ans[step].y = y;
if(flag)
return;
//满足条件输出路径
if(step == p*q && !flag)
{
flag = 1;
for(i = 1;i <= step;i++)
{
printf("%c",ans[i].x - 1 + 'A');
printf("%d",ans[i].y);
}
printf("\n\n");
return;
}
//搜索骑士所能行走的8个方向
for(i = 0;i < 8;i++)
{
tx = x + next[i][0];
ty = y + next[i][1];
if(tx >= 1 && tx <= q && ty >= 1 && ty <= p && !book[tx][ty])
{
book[tx][ty] = 1;
dfs(tx, ty, step+1);
book[tx][ty] = 0;
}
}
}
int main()
{
int i,n;
scanf("%d",&n);
for(i = 1;i <= n;i++)
{
memset(book, 0, sizeof(book));
flag = 0;
scanf("%d %d",&p,&q);
printf("Scenario #%d:\n",i);
//将起点位置A1标记已走
book[1][1] = 1;
dfs(1,1,1);
if(!flag)
printf("impossible\n\n");
}
return 0;
}