poj 2488 A Knight's Journey(dfs)
Description
Background
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
3
1 1
2 3
4 3
Sample Output
Scenario #1:
A1
Scenario #2:
impossible
Scenario #3:
A1B3C1A2B4C2A3B1C3A4B2C4
题意: 在n*m的格子里按照给定的八种方式跳跃能不能走完所有格子 如果能 按照字典序输出(这是个大坑)
还要注意每组要有一个空行
思路:直接按照顺序进行深度搜索 反正最多也只有到26
注意:1.标记数组要记得回溯
2.每个样例输出换行
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int mat[10][10],vis[10][10];
struct root
{
int x;
int y;
};
root ans[100];
int n,m;
int ok;
int op[8][2]={{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};
bool flag(int x,int y)
{
if(x>=0&&x<n&&y>=0&&y<m) return true;
return false;
}
void dfs(int i,int j,int rt)
{
if(ok) return ;
ans[rt].x=i;
ans[rt].y=j;
if(rt==n*m-1)
{
ok=1; return ;
}
for(int k=0;k<8;k++)
{
int x=i+op[k][0];
int y=j+op[k][1];
if(flag(x,y)&&vis[x][y]==0)
{
vis[x][y]=1;
dfs(x,y,rt+1);
vis[x][y]=0;
}
}
}
int main()
{
int t;
int i,j;
int cas=1;
scanf("%d",&t);
while(t--)
{
ok=0;
memset(vis,0,sizeof(vis));
scanf("%d%d",&n,&m);
for(i=0;i<n;i++)
{
if(ok) break;
for(j=0;j<m;j++)
{
if(ok) break;
vis[i][j]=1;
dfs(i,j,0);
vis[i][j]=0;
}
}
printf("Scenario #%d:\n",cas++);
if(!ok) printf("impossible\n\n");
else
{
for(i=0;i<n*m;i++)
{
printf("%c%d",ans[i].y+'A',ans[i].x+1);
}
printf("\n\n");
}
}
return 0;
}

浙公网安备 33010602011771号