A knight's journey
Time limit:1000 ms |
|
Memory limit:65536 K |
Total submissions:29226 |
|
Accepted:10023 |
Description
Background
The knight is getting bored of seeing the same black and white squares 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 between different square numbers 1 ,..., P exist, Q describes how many different square letters exist. these are the first Q letters of the Latin alphabet: ,...
Output
The output for every scenario begins with a line ining "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 shoshould 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 shoshould output impossible on a single line.
Sample Input
31 12 34 3
Sample output
Scenario #1:A1Scenario #2:impossibleScenario #3:A1B3C1A2B4C2A3B1C3A4B2C4
Shen suo Shui question, and the main direction is defined.
The AC code is as follows:
#include<iostream>#include<cstring>using namespace std;struct H{ int x; char y;}b[30],c[30];int dx[8]={-1,1,-2,2,-2,2,-1,1};int dy[8]={-2,-2,-1,-1,1,1,2,2};int a[30][30],vis[30][30];int n,m,bj;void dfs(int h,int z,int cur){ int i; if(cur==n*m) { if(bj==0) { for(i=0;i<cur;i++) cout<<b[i].y<<b[i].x; cout<<endl<<endl; bj=1; } } else { for(i=0;i<8;i++) { int xx,yy; xx=h+dx[i]; yy=z+dy[i]; if(!vis[xx][yy]&&xx>=1&&xx<=n&&yy>=1&&yy<=m) { vis[xx][yy]=1; b[cur].x=xx;b[cur].y=(char)(yy+'A'-1); dfs(xx,yy,cur+1); vis[xx][yy]=0; } } }}int main(){ int t,cas=0; cin>>t; while(t--) { cas++; memset(a,0,sizeof a); memset(vis,0,sizeof vis); cin>>n>>m; bj=0; b[0].x=1;b[0].y=1+'A'-1; vis[1][1]=1; cout<<"Scenario #"<<cas<<":"<<endl; dfs(1,1,1); if(bj==0) { cout<<"impossible"<<endl<<endl; } } return 0;}