广度搜素,用链表写的,代码很差,时间也很慢。不知道还有什么好方法,貌似是有的,有人用0ms过了。
#include <iostream>
int chess[301][301]={0};
using namespace std;
typedef struct bound
{
int x;
int y;
int count;
struct bound *next;
}Set;
int main()
{
int n;
cin >>n;
while(n--)
{
int line;
int sx,sy;
int dx,dy;
cin >>line>>sx>>sy>>dx>>dy;
Set *f,*r,*t;
t=new Set;
f=t;
r=t;
t->x=sx;
t->y=sy;
t->count=0;
chess[sx][sy]=-1;
for(int i=0;i<line;i++)
for(int j=0;j<line;j++)
chess[i][j]=0;
if(dx==sx&&dy==sy)
{
cout<<"0"<<endl;
}
else
{
while(1)
{
if(f->x-2>=0&&f->y+1<=(line-1)&&chess[f->x-2][f->y+1]==0)
{
t=new Set;
t->x=f->x-2;
t->y=f->y+1;
t->count=f->count+1;
r->next=t;
r=t;
chess[t->x][t->y]=-1;
if(t->x==dx&&t->y==dy)
{
cout<<t->count<<endl;
break;
}
}
if(f->x-1>=0&&f->y+2<=(line-1)&&chess[f->x-1][f->y+2]==0)
{
t=new Set;
t->x=f->x-1;
t->y=f->y+2;
t->count=f->count+1;
r->next=t;
r=t;
chess[t->x][t->y]=-1;
if(t->x==dx&&t->y==dy)
{
cout<<t->count<<endl;
break;
}
}
if(f->x+1<=(line-1)&&f->y+2<=(line-1)&&chess[f->x+1][f->y+2]==0)
{
t=new Set;
t->x=f->x+1;
t->y=f->y+2;
t->count=f->count+1;
r->next=t;
r=t;
chess[t->x][t->y]=-1;
if(t->x==dx&&t->y==dy)
{
cout<<t->count<<endl;
break;
}
}
if(f->x+2<=(line-1)&&f->y+1<=(line-1)&&chess[f->x+2][f->y+1]==0)
{
t=new Set;
t->x=f->x+2;
t->y=f->y+1;
t->count=f->count+1;
r->next=t;
r=t;
chess[t->x][t->y]=-1;
if(t->x==dx&&t->y==dy)
{
cout<<t->count<<endl;
break;
}
}
if(f->x+2<=(line-1)&&f->y-1>=0&&chess[f->x+2][f->y-1]==0)
{
t=new Set;
t->x=f->x+2;
t->y=f->y-1;
t->count=f->count+1;
r->next=t;
r=t;
chess[t->x][t->y]=-1;
if(t->x==dx&&t->y==dy)
{
cout<<t->count<<endl;
break;
}
}
if(f->x+1<=(line-1)&&f->y-2>=0&&chess[f->x+1][f->y-2]==0)
{
t=new Set;
t->x=f->x+1;
t->y=f->y-2;
t->count=f->count+1;
r->next=t;
r=t;
chess[t->x][t->y]=-1;
if(t->x==dx&&t->y==dy)
{
cout<<t->count<<endl;
break;
}
}
if(f->x-1>=0&&f->y-2>=0&&chess[f->x-1][f->y-2]==0)
{
t=new Set;
t->x=f->x-1;
t->y=f->y-2;
t->count=f->count+1;
r->next=t;
r=t;
chess[t->x][t->y]=-1;
if(t->x==dx&&t->y==dy)
{
cout<<t->count<<endl;
break;
}
}
if(f->x-2>=0&&f->y-1>=0&&chess[f->x-2][f->y-1]==0)
{
t=new Set;
t->x=f->x-2;
t->y=f->y-1;
t->count=f->count+1;
r->next=t;
r=t;
chess[t->x][t->y]=-1;
if(t->x==dx&&t->y==dy)
{
cout<<t->count<<endl;
break;
}
}
t=f;
f=f->next;
delete t;
}
// cout<<f->count<<endl;
}
}
return 0;
}