骑士移动题解
我又来写题解了~~~
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=305;
bool mp[maxn][maxn];
int sx,sy,tx,ty,l;
int tox[]={1,2,2,1,-1,-2,-2,-1};
int toy[]={2,1,-1,-2,-2,-1,1,2};
struct Node{
int x,y,s;
};
bool judge(Node n){
if(n.x>=0&&n.x<l&&n.y>=0&&n.y<l&&!mp[n.x][n.y]) return true;
return false;
}
int bfs(){
Node now,nxt;
queue<Node>q;
now.x=sx;
now.y=sy;
now.s=0;
q.push(now);
mp[now.x][now.y]=true;
while(!q.empty()){
now=q.front();
q.pop();
if(now.x==tx&&now.y==ty) return now.s;
for(int i=0;i<8;i++){
nxt.x=now.x+tox[i];
nxt.y=now.y+toy[i];
nxt.s=now.s+1;
if(judge(nxt)){
q.push(nxt);
mp[nxt.x][nxt.y]=true;
}
}
}
return -1;
}
int main()
{
freopen("move.in","r",stdin);
freopen("move.out","w",stdout);
int n;
scanf("%d",&n);
while(n--){
memset(mp,false,sizeof(mp));
scanf("%d",&l);
scanf("%d%d",&sx,&sy);
scanf("%d%d",&tx,&ty);
int ans=bfs();
printf("%d\n",ans);
}
return 0;
}
浙公网安备 33010602011771号