题目
题目描述
小明是一名出色的棋手,声称没有人能像他那样快速地把骑士从一个位置移到另一个位置,你能打败他吗?
编写一个程序,计算一个骑士从棋盘上的一个格子到另一个格子所需的最小步数。骑士一步可以移动到的位置由下图给出。
输入
第一行给出骑士的数量 n。对于每一个骑士都有3行,第一行一个整数 L 表示棋盘的大小(4≤L≤300),整个棋盘大小为 L×L;
第二行和第三行分别包含一对整数 (x,y),表示骑士的起始点和终点。假设对于每一个骑士,起始点和终点均合理。
输出
对每一个骑士输出一行,一个整数表示需要移动的最小步数。如果起始点和终点相同,则输出 0。
样例输入
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
样例输出
5
28
0分析这道题是一道广搜题,用深搜可能会时间超限。这道题难度也不低,代码很长,需要用到队列queue代码
#include<bits/stdc++.h>
using namespace std;
bool vis[
301][
301];
int step[
301][
301],ans,t,n,sx,sy,ex,ey,nx,ny;
int main()
{
scanf("%d",&
t);
while(t--
){
scanf("%d%d%d%d%d",&n,&sx,&sy,&ex,&
ey);
queue<
int>
qx,qy;
qx.push(sx),qy.push(sy);
vis[sx][sy]=
1;
step[sx][sy]=
0;
while(!qx.empty()&&!
qy.empty()){
nx=
qx.front(),qx.pop();
ny=
qy.front(),qy.pop();
if(nx==ex&&ny==
ey){
ans=step[ex][ey];
//如果达到终点,则停止
break;
}
if(nx-
2>=
0&&ny+
1<=n&&vis[nx-
2][ny+
1]==
0)
//八个方向开始搜索
{
qx.push(nx-
2);
qy.push(ny+
1);
step[nx-
2][ny+
1]=step[nx][ny]+
1;
vis[nx-
2][ny+
1]=
1;
}
if(nx-
2>=
0&&ny-
1>=
0&&vis[nx-
2][ny-
1]==
0)
{
qx.push(nx-
2);
qy.push(ny-
1);
step[nx-
2][ny-
1]=step[nx][ny]+
1;
vis[nx-
2][ny-
1]=
1;
}
if(nx-
1>=
0&&ny+
2<=n&&vis[nx-
1][ny+
2]==
0)
{
qx.push(nx-
1);
qy.push(ny+
2);
step[nx-
1][ny+
2]=step[nx][ny]+
1;
vis[nx-
1][ny+
2]=
1;
}
if(nx-
1>=
0&&ny-
2>=
0&&vis[nx-
1][ny-
2]==
0)
{
qx.push(nx-
1);
qy.push(ny-
2);
step[nx-
1][ny-
2]=step[nx][ny]+
1;
vis[nx-
1][ny-
2]=
1;
}
if(nx+
1<=n&&ny+
2<=n&&vis[nx+
1][ny+
2]==
0)
{
qx.push(nx+
1);
qy.push(ny+
2);
step[nx+
1][ny+
2]=step[nx][ny]+
1;
vis[nx+
1][ny+
2]=
1;
}
if(nx+
2<=n&&ny+
1<=n&&vis[nx+
2][ny+
1]==
0)
{
qx.push(nx+
2);
qy.push(ny+
1);
step[nx+
2][ny+
1]=step[nx][ny]+
1;
vis[nx+
2][ny+
1]=
1;
}
if(nx+
2<=n&&ny-
1>=
0&&vis[nx+
2][ny-
1]==
0)
{
qx.push(nx+
2);
qy.push(ny-
1);
step[nx+
2][ny-
1]=step[nx][ny]+
1;
vis[nx+
2][ny-
1]=
1;
}
if(nx+
1<=n&&ny-
2>=
0&&vis[nx+
1][ny-
2]==
0)
{
qx.push(nx+
1);
qy.push(ny-
2);
step[nx+
1][ny-
2]=step[nx][ny]+
1;
vis[nx+
1][ny-
2]=
1;
}
}
printf("%d\n",ans);
memset(vis,0,
sizeof(vis));
//因为有多组样例,所以需要置零
memset(step,
0,
sizeof(step));
nx=
0,ny=
0,ans=
0;
while(!qx.empty()&&!qy.empty()){
//清空队列
qx.pop();
qy.pop();
}
}
return 0;
}
转载于:https://www.cnblogs.com/earth833/p/11168292.html
转载请注明原文地址: https://win8.8miu.com/read-11357.html