#include <iostream>
using namespace std;
int path[60][2];
int success,visited[8][8],p,q,k;
int dirx[8]={-1,1,-2,2,-2,2,-1,1};
int diry[8]={-2,-2,-1,-1,1,1,2,2};
int check(int x,int y)
{
if(x>=0&&x<p&&y>=0&&y<q)
return 1;
else return 0;
}
int is_end()
{
for (int i=0;i<p;++i)
{
for (int j=0;j<q;++j)
{
if(!visited[i][j])
return 0;
}
}
return 1;
}
void DFS(int x,int y)
{
int flag=0;
visited[x][y]=1;
//cout << x << y << endl;
int px,py;
for (int i=0;!success&&i<8;++i)
{
px=x+dirx[i];
py=y+diry[i];
if(check(px,py)&&!visited[px][py])
{
flag=1;
DFS(px,py);
}
}
if(!flag&&is_end())
{
success=1;
}
if(success==1)
{
path[k][0]=x;
path[k++][1]=y;
}
if(success!=1)
visited[x][y]=0;
}
int main()
{
int n,i=0;
cin >> n;
while (n--)
{
cin >> p >> q;
success=0;
k=0;
printf("Scenario #%d:\n",++i);
memset(visited,0,sizeof(visited));
memset(path,0,sizeof(visited));
for (int i=0;i<p;++i)
{
for (int j=0;j<q;++j)
{
DFS(i,j);
if(success)
break;
}
if(success)
break;
}
if(success)
{
for (k=k-1;k>=0;k--)
{
printf("%c%c",path[k][1]+'A',path[k][0]+'1');
}
cout << endl;
}
else
{
cout << "impossible" << endl;
}
cout << endl;
}
}
完全是抄的代码。。。完全不会写递归。。。麻烦。。。中间的那个flag不要也正确,但是可以省去不必要的检查,学习写递归
![睡觉](http://static.blog.csdn.net/xheditor/xheditor_emot/default/sleep.gif)
![睡觉](http://static.blog.csdn.net/xheditor/xheditor_emot/default/sleep.gif)
![睡觉](http://static.blog.csdn.net/xheditor/xheditor_emot/default/sleep.gif)