题目
题目描述
编写一个程序,计算一个骑士从棋盘上的一个格子到另一个格子所需的最小步数。骑士一步可以移动到的位置由下图给出。
输入格式
第一行给出骑士的数量 n。
在接下来的 3n 行中,每 3 行描述了一个骑士。其中,
第一行一个整数 L 表示棋盘的大小,整个棋盘大小为
L
×
L
L\times L
L×L;
第二行和第三行分别包含一对整数 (x,y),表示骑士的起始点和终点。假设对于每一个骑士,起始点和终点均合理。
输出格式
对每一个骑士,输出一行一个整数表示需要移动的最小步数。如果起始点和终点相同,则输出 0。
样例
输入
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
输出
5
28
0
代码详解
#include<bits/stdc++.h>
using namespace std;
struct node{
int x;
int y;
int step;
bool operator ==(const node &t){
return x==t.x&&y==t.y;
}
}fir,las,now,fut;
int n;
queue<node> q;
int dx[]={1,1,-1,-1,2,2,-2,-2};//8个方向
int dy[]={2,-2,2,-2,1,-1,1,-1};
bool vis[505][505];
bool check(int,int);
void bfs();
int main()
{
int T;
cin>>T;
while(T--){
cin>>n;
cin>>fir.x>>fir.y;
cin>>las.x>>las.y;
fir.step=0;//初始为0
memset(vis,0,sizeof(vis));//初始化为false
vis[fir.x][fir.y]=1;//把出发点打上标记
while(!q.empty()){//把队列清空
q.pop();
}
q.push(fir);//从出发点开始搜
bfs();
}
return 0;
}
bool check(int x,int y){
if(x>=0&&x<=n&&y>=0&&y<=n&&!vis[x][y]){
return true;
}
return false;
}
void bfs(){
while(!q.empty()){
now=q.front();//取队头
q.pop();
if(now==las){
cout<<now.step<<endl;
return;
}
for(int i=0;i<8;i++){
fut.x=now.x+dx[i];
fut.y=now.y+dy[i];//向对应方向移动
if(check(fut.x,fut.y)){//检查是否在范围里和是否已经走过
fut.step=now.step+1;//步数++
vis[fut.x][fut.y]=1;//打标记
q.push(fut);
}
}
}
}
end
广搜模板题