#include<iostream>
#include<queue>
using namespace std;
struct d_node{
int a,b;
};
d_node d[8]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
int visited[8][8];
struct state_node{
int x,y;
int len;
};
void place(state_node k,state_node e);
int main()
{
state_node node_b,node_e;
int x1,y1,x2,y2;
char a[3],b[3];
while(cin>>a>>b)
{
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
visited[i][j]=0;
x1=(int)(a[0]-96);
y1=(int)(a[1]-48);
x2=(int)(b[0]-96);
y2=(int)(b[1]-48);
node_b.x=x1-1;
node_b.y=y1-1;
node_b.len=0;
node_e.x=x2-1;
node_e.y=y2-1;
visited[x1-1][y1-1]=1;
cout<<"To get from ";
cout<<a;
cout<<" to ";
cout<<b;
cout<<" takes ";
place(node_b,node_e);
cout<<" knight moves."<<endl;
}
return 0;
}
void place(state_node k,state_node e)
{
if((k.x==e.x) && (k.y==e.y))
{
cout<<k.len;
return ;
}
queue <state_node> q;
int i=0;
visited[k.x][k.y]=1;
q.push(k);
while(!q.empty())
{
state_node t=q.front();
q.pop();
for(i=0;i<8;i++)
{
state_node kk;
kk.x=t.x+d[i].a;
kk.y=t.y+d[i].b;
if(kk.x>7 || kk.x<0 || kk.y>7 ||kk.y<0)continue;
if(!visited[kk.x][kk.y])
{
kk.len=t.len+1;
visited[kk.x][kk.y]=1;
if((kk.x==e.x) && (kk.y==e.y))
{
cout<<kk.len;
return;
}
q.push(kk);
}
}
}
}
注:求最小步数,一般采用广搜。
poj2243 Knight Moves
最新推荐文章于 2022-03-05 14:41:19 发布
