7 问从起点到终点最少需要多少步 #include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
#include<map>
using namespace std;
const int maxn = 100;
int map[maxn][maxn];
int vis[maxn][maxn];
int re[maxn][maxn];
char Start[maxn];
char End[maxn];
int t;
int ans;
int sx,sy,ex,ey;
int fx[8] = {0,0,1,-1,1,1,-1,-1};
int fy[8] = {1,-1,0,0,-1,1,1,-1};
struct Point
{
int x;
int y;
};
Point start,nex,temp;
void bfs(int sx,int sy,int ex,int ey)
{
queue<Point>Q;
vis[sx][sy] = 1;
start.x = sx;
start.y = sy;
Q.push(start);
while(!Q.empty())
{
temp = Q.front();
Q.pop();
if(temp.x == ex && temp.y == ey) return;
for(int i=0;i<8;i++)
{
nex.x = fx[i] + temp.x;
nex.y = fy[i] + temp.y;
if(nex.x >= 1 && nex.x <= 8 && nex.y >= 1 && nex.y <=8 && vis[nex.x][nex.y] == 0)
{
vis[nex.x][nex.y] = 1;
re[nex.x][nex.y] = re[temp.x][temp.y] + 1;
ans++;
Q.push(nex);
}
}
}
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%s",&Start);
scanf("%s",&End);
sx = Start[0] - 'a' + 1;
sy = Start[1] - '0';
ex = End[0] - 'a' + 1;
ey = End[1] - '0';
ans = 0;
memset(vis,0,sizeof(vis));
memset(re,0,sizeof(re));
bfs(sx,sy,ex,ey);
printf("%d\n",re[ex][ey]);
}
}
|