题意:给出8*8的棋盘,给出起点和终点,问最少走几步到达终点。
因为骑士的走法和马的走法是一样的,走日字形(四个象限的横竖的日字形)
另外字母转换成坐标的时候仔细一点(因为这个WA了两次---@_@)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define maxn 105
using namespace std;
struct node
{
int x,y;
int step;
} now,next,st,en;
queue<node>q;
char m,n;
int vis[maxn][maxn];
int dir[][]={{,},{,},{-,},{-,},{-,-},{-,-},{,-},{,-}};
void bfs(int x,int y)
{
now.x=x;now.y=y;now.step=;
while(!q.empty()) q.pop();
q.push(now);
vis[x][y]=;
while(!q.empty())
{
now=q.front();q.pop();
if(now.x==en.x&&now.y==en.y)
{
printf("To get from %c%d to %c%d takes %d knight moves.\n",m,st.y,n,en.y,now.step);
return;
};
for(int i=;i<;i++)
{
next.x=now.x+dir[i][];
next.y=now.y+dir[i][];
if(next.x<||next.y>||next.y<||next.y>) continue;
if(!vis[next.x][next.y])
{
vis[next.x][next.y]=;
next.step=now.step+;
q.push(next);
if(next.x==en.x&&next.y==en.y)
{
printf("To get from %c%d to %c%d takes %d knight moves.\n",m,st.y,n,en.y,next.step);
return;
}
}
}
}
}
int main()
{
while(cin>>m>>st.y>>n>>en.y)
{
memset(vis,,sizeof(vis));
st.x=m-'a'+;
en.x=n-'a'+;
bfs(st.x,st.y);
}
}