题目意思:hdu1372,问国际象棋中的马从起始位置到目标位置至少要几步。
解题思路:水题,bfs,连坑都没有。
代码明细:
//probID: hdu1372
//author: WiselyQY
//date: 2021-01-04
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int x,y,step;
};
const int INF=1<<30;
int sx,sy,ex,ey,vis[10][10],ans;
char scx,scy,ecx,ecy,g[10][10];
queue<Node> q;
const int dx[]={2,1,-1,-2,-2,-1,1,2}, dy[]={1,2,2,1,-1,-2,-2,-1};
int in(int x, int y)
{
return x>=1 && x<=8 && y>=1 && y<=8;
}
void bfs()
{
while(!q.empty()) q.pop();
memset(vis,0,sizeof(vis));
vis[sx][sy]=1;
Node u;
u.x=sx; u.y=sy; u.step=0;
q.push(u);
while(!q.empty())
{
u=q.front(); q.pop();
int x=u.x, y=u.y, step=u.step;
if(x==ex && y==ey) {ans=step; return;}
for(int i=0; i<8; i++)
{
int nx=x+dx[i], ny=y+dy[i];
if(in(nx,ny) && !vis[nx][ny])
{
vis[nx][ny]=1;
Node nu;
nu.x=nx; nu.y=ny; nu.step=step+1;
q.push(nu);
}
}
}
}
int main()
{
clock_t start,end;
start=clock();
#ifndef ONLINE_JUDGE
freopen(R"(D:\code\hdu\1372\in.txt)","r",stdin);
#endif
while(cin>>scx>>scy>>ecx>>ecy)
{
sx=scx-'a'+1; sy=scy-'0';
ex=ecx-'a'+1; ey=ecy-'0';
ans=INF;
bfs();
cout<<"To get from "<<scx<<scy<<" to "<<ecx<<ecy<<" takes "<<ans<<" knight moves."<<endl;
}
end=clock();
//printf("time=%lfs\n",(double)(end-start)/1000);
return 0;
}