不解释的BFS。
#include <stdio.h>
#include <string.h>
#define MAXM (300+5)
typedef struct {
int x;
int y;
int d;
}Node;
Node queue[MAXM*MAXM];
int front,rear;
int dir[8][2]={ {-2,1},{-1,2},{1,2},{2,1}, {2,-1},{1,-2},{-1,-2},{-2,-1} };
int visit[MAXM][MAXM];
int M;
int Q_empty()
{
if( rear == front ) return 1;
return 0;
}
Node Q_front()
{
if( Q_empty() ) return ;
return queue[front];
}
void Q_pop()
{
front = (front+1) % (MAXM*MAXM);
}
void Q_push( Node cur )
{
queue[rear]= cur;
rear = (rear+1) % (MAXM*MAXM) ;
}
int in_map(Node cur)
{
if( cur.x>=0 && cur.x <M && cur.y>=0 && cur.y <M)
return 1;
return 0;
}
int bfs( Node from , Node to )
{
int i;
Node a,cur;
if( from.x == to.x && from.y == to.y ) return 0;
from.d=0;
Q_push(from);
visit[from.x][from.y]=1;
while( !Q_empty() )
{
a = Q_front();
Q_pop();
cur.d= a.d + 1;
for( i=0 ; i < 8 ; i++)
{
cur.x= a.x + dir[i][0];
cur.y= a.y + dir[i][1];
if( in_map(cur) && !visit[cur.x][cur.y] )
{
if( cur.x==to.x && cur.y==to.y )
return cur.d;
Q_push(cur);
visit[cur.x][cur.y]=1;
}
}
}
return -1;
}
int main()
{
int n;
int i;
Node from,to;
// freopen("test.in","r",stdin);
while(~scanf("%d",&n))
{
for(i=0;i<n;i++)
{
scanf("%d",&M);
memset(visit,0,sizeof(visit));
front=rear=0;
scanf("%d%d",&from.x,&from.y);
scanf("%d%d",&to.x,&to.y);
printf("%d\n",bfs(from,to));
}
}
return 0;
}