大意就是给定大小棋盘,可以以任意位置为起点,让马跳遍棋盘的每个位置而不重复,普通的DFS
#include<iostream>
#include<cstring>
using namespace std;
int chess[30][30]; //标记棋盘当前位置是否走过
char ans[100000]; //存答案
int p,q;
int cnt; //记录已走过点的个数
bool dfs(int x,int y)
{
if(cnt==p*q)
return true;
if(x<1||y<1||x>p||y>q||chess[x][y]==1)
return false;
ans[cnt*2]=x+'A'-1;
ans[cnt*2+1]=y+'0';
chess[x][y]=1;
cnt++;
if(dfs(x-2,y-1)) //题目要求的顺序,字典序
return true;
if(dfs(x-2,y+1))
return true;
if(dfs(x-1,y-2))
return true;
if(dfs(x-1,y+2))
return true;
if(dfs(x+1,y-2))
return true;
if(dfs(x+1,y+2))
return true;
if(dfs(x+2,y-1))
return true;
if(dfs(x+2,y+1))
return true;
cnt--;
chess[x][y]=0;
return false;
}
bool loop() //循环每个起点,判断当前起点成不成立
{
for(int i=1; i<=p; i++)
for(int j=1; j<=q; j++)
if(dfs(i,j))
return true;
return false;
}
int main()
{
int n;
int num=1;
cin>>n;
while(n--)
{
for(int i=0; i<30; i++)
for(int j=0; j<30; j++)
chess[i][j]=0;
memset(ans,0,100000);
cnt=0;
cin>>q>>p;
cout<<"Scenario #"<<num++<<":"<<endl;
if(loop())
{
ans[cnt*2]=0;
cout<<ans<<endl;
}
else
cout<<"impossible"<<endl;
cout<<endl;
}
}