搜索 B

来源:互联网 发布:帕拉卡斯人知乎 编辑:程序博客网 时间:2024/06/05 10:31

Description

Background
The knight is getting bored of seeing the same black and white squares again and again and has decided to make a journey 
around the world. Whenever a knight moves, it is two squares in one direction and one square perpendicular to this. The world of a knight is the chessboard he is living on. Our knight lives on a chessboard that has a smaller area than a regular 8 * 8 board, but it is still rectangular. Can you help this adventurous knight to make travel plans? 

Problem
Find a path such that the knight visits every square once. The knight can start and end on any square of the board.

Input

The input begins with a positive integer n in the first line. The following lines contain n test cases. Each test case consists of a single line with two positive integers p and q, such that 1 <= p * q <= 26. This represents a p * q chessboard, where p describes how many different square numbers 1, . . . , p exist, q describes how many different square letters exist. These are the first q letters of the Latin alphabet: A, . . .

Output

The output for every scenario begins with a line containing "Scenario #i:", where i is the number of the scenario starting at 1. Then print a single line containing the lexicographically first path that visits all squares of the chessboard with knight moves followed by an empty line. The path should be given on a single line by concatenating the names of the visited squares. Each square name consists of a capital letter followed by a number. 
If no such path exist, you should output impossible on a single line.

Sample Input

31 12 34 3

Sample Output

Scenario #1:A1Scenario #2:impossibleScenario #3:A1B3C1A2B4C2A3B1C3A4B2C4


            这道题为一道DFS题,要求骑士能把所有方格走一遍,输出一种走的路径。思路就是从A1开始向8个方位搜索,若满足条件,则跳过去,直到把所有格子跳一遍为止。


源代码如下:

#include<iostream> 
#include<cstring> 
#include<cstdio>
#include<cstdlib>
using namespace std;
int p,q,h,z,b[100][100],a2[100],f[10][10]={{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};
char a1[100];
void DFS(int x,int y,int h)
{
int i,j;
if(h==p*q)
 {
  for(i=0;i<h;++i)
   cout<<a1[i]<<a2[i];
 cout<<endl;
 z=0;
 
 }

else for(i=0;i<8;++i)
{
if(x+f[i][0]>=1&&x+f[i][0]<=p&&y+f[i][1]>=1&&y+f[i][1]<=q&&b[x+f[i][0]][y+f[i][1]]==0&&z)
{   b[x+f[i][0]][y+f[i][1]]=1;
a1[h]=y+f[i][1]-1+'A';
a2[h]=x+f[i][0];
DFS(x+f[i][0],y+f[i][1],h+1);
b[x+f[i][0]][y+f[i][1]]=0;
}
}
 
}
int main()
{
int n,k=0;
cin>>n;
while(n--)
{   k++;
   
   z=1;
   memset(a1,'\0',sizeof(a1));
   memset(a2,0,sizeof(a2));
   a1[0]='A';
   a2[0]=1;
   memset(b,0,sizeof(b));
   b[1][1]=1;
cin>>p>>q;
cout<<"Scenario #"<<k<<":"<<endl;
DFS(1,1,1);
if(z)cout<<"impossible"<<endl;
if(n!=0)cout<<endl;
}
}