一个搜索的题目,按照八个方向,不过输入的时候要将字母转换一下,在进行计算。
#include<iostream>
#include<cstring>
#include<string>
#include<queue>
using namespace std;
struct Node
{
int x;
int y;
int step;
};
int dir[8][2]={-2,-1,-2,1,-1,-2,-1,2,1,-2,1,2,2,-1,2,1};
int bfs(string st,string end)
{
bool visit[10][10];
memset(visit,false,sizeof(visit));
Node s,e,t;
queue<Node> q;
s.x=st[0]-'a';
s.y=st[1]-'0';
s.step=0;
e.x=end[0]-'a';
e.y=end[1]-'0';
if(s.x==e.x&&s.y==e.y)
return 0;
q.push(s);
visit[s.x][s.y]=true;
while(!q.empty())
{
s=q.front();
q.pop();
for(int i=0;i<8;++i)
{
t.x=s.x+dir[i][0];
t.y=s.y+dir[i][1];
t.step=s.step+1;
if(visit[t.x][t.y]==false)
{
if(t.x==e.x&&t.y==e.y)
return t.step;
if(t.x>=0&&t.x<8&&t.y>0&&t.y<=8)
{
visit[t.x][t.y]=true;
q.push(t);
}
}
}
}
}
int main()
{
string st,end;
while(cin>>st>>end)
{
cout<<"To get from "<<st<<" to "<<end<<" takes "<<bfs(st,end)<<" knight moves."<<endl;
}
return 0;
}