搜索 B题

来源:互联网 发布:淘宝购物如何追加评论 编辑:程序博客网 时间:2024/05/28 19:25
B - 02
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit Status

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
2.解题思路:
   

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

3.代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
using namespace std;
int p,q,h,visit,b[100][100],c[100];
int f[10][10]={{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};
char map[100];
void dfs(int x,int y,int h)
{


int i,j;
if(h==p*q)
 {
  for(i=0;i<h;++i)
   cout<<map[i]<<c[i];
   cout<<endl;
   visit=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&&visit)
{   b[x+f[i][0]][y+f[i][1]]=1;
map[h]=y+f[i][1]-1+'A';
c[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++;


   visit=1;
   memset(map,'\0',sizeof(map));
   memset(c,0,sizeof(c));
   map[0]='A';
   c[0]=1;
   memset(b,0,sizeof(b));
   b[1][1]=1;
cin>>p>>q;
cout<<"Scenario #"<<k<<":"<<endl;
dfs(1,1,1);
if(visit)
cout<<"impossible"<<endl;
if(n!=0)
cout<<endl;
}
}




原创粉丝点击