原题面:
输L代表有个L×L的棋盘,输入开始位置的坐标和结束位置的坐标,问一个骑士朝棋盘的八个方向走马字步,从开始坐标到结束坐标可以经过多少步。
首先输入一个T,表示测试样例的个数。
每个测试样例有三行。
第一行是棋盘的大小L (4 ≤ L ≤ 300) ;
第二行和第三行分别表示马的起始位置和目标位置(0..L−1)。
马移动的最小步数,起始位置和目标位置相同时输出0。
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
5
28
0
我的代码:
#include<cstdio>
#include<cstring>
#include<cassert>
#include<queue>
#include<map>
using namespace std;
inline int read()
{
int x=0,w=1;
char ch=0;
while(ch<'0'||ch>'9')
{
if(ch=='-') w=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
x=(x<<1)+(x<<3)+(ch^'0');
ch=getchar();
}
return x*w;
}
inline void write(int x)
{
if(x<0)
{
x=-x;
putchar('-');
}
if(x>9) write(x/10);
putchar((x%10)^48);
}
struct statu
{
int x,y,step;
bool operator==(const statu& ano) const {
return ano.x == x && ano.y == y;
}
};
bool operator< (const statu& x,const statu& y)
{
if(x.x!=y.x) return x.x<y.x;
if(x.y!=y.y) return x.y<y.y;
if(x.step!=y.step) return x.step<y.step;
return 0;
}
const int dx[]={-1,-2,-2,-1,1,2,2,1};
const int dy[]={2,1,-1,-2,2,1,-1,-2};
inline void bfs(int l,int x1,int y1,int x2,int y2)
{
if(x1==x2&&y1==y2)
{
putchar('0');
putchar('\n');
return;
}
queue<statu> q;
map<statu,int> vis;
q.push(statu{x1,y1,0});
q.push(statu{x2,y2,0});
vis[statu{x1,y1,0}]=1;
vis[statu{x2,y2,0}]=2;
while(!q.empty())
{
statu now=q.front();
vector<statu> nstatus;
q.pop();
for(int i=0;i<8;i++)
{
statu nstatu={now.x+dx[i],now.y+dy[i],now.step+1};
if(nstatu.x>=0&&nstatu.x<l&&nstatu.y>=0&&nstatu.y<l) nstatus.push_back(nstatu);
}
for(auto i:nstatus)
{
if(vis[i]!=0&&vis[now]!=0&&vis[i]!=vis[now])
{
write(now.step+i.step);
putchar('\n');
return;
}
if(vis[i]==0)
{
if(vis[now]==1)
{
vis[i]=1;
q.push(i);
}
if(vis[now]==2)
{
vis[i]=2;
q.push(i);
}
}
}
}
}
int main()
{
int n=read();
for(int i=1;i<=n;i++)
{
int l=read(),x1=read(),y1=read(),x2=read(),y2=read();
bfs(l,x1,y1,x2,y2);
}
return 0;
}
用双向搜索写的,现在问题是死循环,求助