Problem : A Knight’s Journey
Description:给你一个棋盘,问骑士能否不重复的游历整个棋盘。骑士可以运动的方向如题目图所示。
Solution:深度优先搜索。题目要求按字典序输出,所以一定要注意搜索的顺序。
Code(C++):
#include <iostream>
#include <cstring>
using namespace std;
struct point
{
int x;
int y;
} index[8];
int c[100][100];
int n,len,wid;
char ans[1000];
int k;
int count;
bool dfs(point p)
{
point next;
if(count==len*wid)
return true;
for(int i=0; i<8; i++)
{
next.x=p.x+index[i].x;
next.y=p.y+index[i].y;
if(next.x>=0&&next.y>=0&&next.x<wid
&&next.y<len&&c[next.x][next.y]==0)
{
c[next.x][next.y]=1;
count++;
ans[k++]='A'+next.x;
ans[k++]='1'+next.y;
if(dfs(next))
return true;
c[next.x][next.y]=0;
count--;
k-=2;
}
}
return false;
}
int main()
{
index[0].x=-2;index[0].y=-1;
index[1].x=-2;index[1].y=1;
index[2].x=-1;index[2].y=-2;
index[3].x=-1;index[3].y=2;
index[4].x=1;index[4].y=-2;
index[5].x=1;index[5].y=2;
index[6].x=2;index[6].y=-1;
index[7].x=2;index[7].y=1;
cin>>n;
int q=1;
while(n--)
{
memset(c,0,sizeof(c));
count=1;
k=2;
memset(ans,'0',sizeof(ans));
cin>>len>>wid;
point here;
here.x=0;
here.y=0;
cout<<"Scenario #"<<q++<<":"<<endl;
c[here.x][here.y]=1;
ans[0]='A';
ans[1]='1';
if(dfs(here))
{
for(int i=0; i<k; i++)
cout<<ans[i];
cout<<endl;
}
else
cout<<"impossible"<<endl;
cout<<endl;
}
return 0;
}