给定一个 p x q 的棋盘,请判断马能否不重复的走过所有格,并记录下其中按字典序排列的第一种路径。
#include<bits/stdc++.h>
using namespace std;
int dx[8][2]={-1,-2,1,-2,-2,-1,2,-1,-2,1,2,1,-1,2,1,2};
int book[8][8];
int mx,my;
bool check(int a,int b)
{
if(book[a][b]==0&&a>=0&&a<mx&&b>=0&&b<my)
{
return true;
}
return false;
}
struct nd
{
int x,y;
};
deque<nd> k;
void print()
{
nd t;
cout<<"A1";
while(!k.empty())
{
t=k.front();
char l;
l=t.y+65;
cout<<" "<<l<<t.x+1;
k.pop_front();
}
cout<<endl;
}
bool dfs(int x,int y)
{
int t;
for(int i=0;i<mx;i++)
{
for(int j=0;j<my;j++)
{
if(book[i][j]!=1) t=1;
}
if(t==1)
{
break;
}
}
if(t==0)
{
return true;
}
for(int i=0;i<8;i++)
{
int row=x+dx[i][0],col=y+dx[i][1];
if(check(row,col))
{
book[row][col]=1;
if(dfs(row,col))
{
nd t;
t.x=row;
t.y=col;
k.push_front(t);
return true;
}
else
{
book[row][col]=0;
k.clear();
}
}
}
return false;
}
int main()
{
int i;
scanf("%d",&mx);
scanf("%d",&my);
book[0][0]=1;
if(mx==1&&my==1)
{
printf("%s","A1");
}
else if(dfs(0,0)==false)
{
printf("%s","impossible");
}
else
{
print();
}
memset(book,0,sizeof(book));
k.clear();
return 0;
}