#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<vector>
#include<map>
#include<stack>
#include<queue>
#include<set>
#define maxn 305
#define INF 0x3f3f3f3f
#define MOD 1000000007
#define LL long long
#define e 2.71828182
using namespace std;
int n;
int nextz[8][2]={2,1,1,2,2,-1,1,-2,-2,1,-2,-1,-1,2,-1,-2};
int book[maxn][maxn];
int sx,sy,ex,ey;
struct node
{
int x,y;
};
int step[maxn][maxn];
void bfs()//双向广搜
{
memset(book,0,sizeof(book));
memset(step,0,sizeof(step));
queue<node>q;
node h,h1,h2,t;
h1.x=sx;h1.y=sy;
h2.x=ex;h2.y=ey;
q.push(h1);book[sx][sy]=1;
q.push(h2);book[ex][ey]=2;
int tx,ty;
int ans,flag;
flag=0;
while(!q.empty())
{
h=q.front();
q.pop();
for(int i=0;i<8;i++)
{
tx=h.x+nextz[i][0];
ty=h.y+nextz[i][1];
if(tx<0||ty<0||tx>=n||ty>=n)
continue;
if(book[tx][ty]&&book[h.x][h.y]&&book[tx][ty]!=book[h.x][h.y])
{
flag=1;
ans=step[h.x][h.y]+step[tx][ty]+1;
break;
}
if(!book[tx][ty])
{
t.x=tx;
t.y=ty;
q.push(t);
step[tx][ty]=step[h.x][h.y]+1;
book[tx][ty]=book[h.x][h.y];
}
}
if(flag)
{
break;
}
}
//cout << flag << endl;
if(flag)
{
cout << ans << endl;
}
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n;
cin>>sx>>sy>>ex>>ey;
if(sx==ex&&sy==ey)
{
cout << 0 << endl;
continue;
}
bfs();
}
return 0;
}
双向广搜
最新推荐文章于 2024-03-01 15:33:55 发布