# POJ 1915_双向BFS

## 前提

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#include <vector>
#include <algorithm>

using namespace std;
const int M = 310;
int vis[M][M],step[M][M],len;
const int dx[8] = {-1,-2,-2,-1,1,2,2,1};
const int dy[8] = {-2,-1,1,2,2,1,-1,-2};
struct node{
int x,y;
node(){}
node(int x,int y):x(x),y(y){}
}st,en;

int limit(node a){
return (a.x >= 0 && a.x < len && a.y >= 0 && a.y < len);
}

int BFS()
{
if(st.x == en.x && st.y == en.y)return 0;
queue<node> que[2];
que[0].push(st);que[1].push(en);
vis[st.x][st.y] = 1;vis[en.x][en.y] = 2;
while(!que[0].empty() && !que[1].empty())
{
if(!que[0].empty())
{
node q = que[0].front();que[0].pop();
for(int i =0 ;i < 8;i ++)
if(limit(node(q.x + dx[i],q.y + dy[i])))
{
node now = node(q.x + dx[i],q.y+dy[i]);
if(vis[now.x][now.y] == 2)
return step[q.x][q.y] + step[now.x][now.y]+1;
else if(!vis[now.x][now.y])
{
vis[now.x][now.y] = 1;
step[now.x][now.y] = step[q.x][q.y] +1;
que[0].push(now);
}
}
}
if(!que[1].empty())
{
node q = que[1].front();que[1].empty();
for(int i = 0;i < 8;i ++)
if(limit(node(q.x + dx[i],q.y+dy[i])))
{
node now = node(q.x + dx[i],q.y + dy[i]);
if(vis[now.x][now.y] == 1)
return step[q.x][q.y] + step[now.x][now.y] +1;
else if(!vis[now.x][now.y])
{
vis[now.x][now.y] = 2;
step[now.x][now.y] = step[q.x][q.y] +1;
que[1].push(now);
}
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&len);
scanf("%d%d%d%d",&st.x,&st.y,&en.x,&en.y);
memset(vis,0,sizeof(vis));
memset(step,0,sizeof(step));
printf("%d\n",BFS());
}
return 0;
}


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120