一道简单的BFS搜索题。
#include <stdio.h>
#include <string.h>
int x1,y1,x2,y2,m;
int z[400][400];
int h[8][2]={{-2,-1},{-1,-2},{-1,2},{-2,1},{1,2},{2,1},{1,-2},{2,-1}};
struct sa
{
int x,y,step;
}data[90001];
int bfs(int x,int y)
{
if (x==x2&&y==y2) return 0;
int r=0,l=0;
data[r].x=x;
data[r].y=y;
data[r++].step=0;
while (l<r)
{
sa now,next;
now.x=data[l].x;
now.y=data[l].y;
now.step=data[l++].step;
for (int b=0;b<8;b++)
{
next.x=now.x+h[b][0];
next.y=now.y+h[b][1];
next.step=now.step+1;
if (next.x>=0&&next.x<m&&next.y>=0&&next.y<m&&z[next.x][next.y]==0)
{
if (next.x==x2&&next.y==y2) return next.step;
z[next.x][next.y]=1;
data[r].x=next.x;
data[r].y=next.y;
data[r++].step=next.step;
}
}
}
return -1;
}
int main()
{
int n,count;
scanf("%d",&n);
while (n--)
{
scanf("%d",&m);
scanf("%d%d",&x1,&y1);
scanf("%d%d",&x2,&y2);
z[x1][y1]=1;
memset(z,0,sizeof(z));
count=bfs(x1,y1);
printf("%d\n",count);
count=0;
}
return 0;
}