HDU 1372

http://acm.hdu.edu.cn/showproblem.php?pid=1372

象棋中给出起点到终点,马最少走几步?马走日子 ,基础的BFS

代码:

#include<iostream>
#include<queue>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
int a[10][10], visit[10][10];
int bx,by,ex,ey;
int XX[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}};
struct node{int x,y,step;};
int BFS(int step)
{
if(bx==ex&&by==ey)return step;
int k,xx,yy,stepp;
queue<node>qu;
node t,tt;
t.x=bx,t.y=by,t.step=0;
qu.push(t);
while(!qu.empty())
{
t=qu.front();
qu.pop();
for(k=0;k<8;k++)
{
xx=t.x+XX[k][0],yy=t.y+XX[k][1],stepp=t.step;
if(xx>0&&xx<=8&&yy>0&&yy<=8&&!visit[xx][yy])
{
visit[xx][yy]=1;
stepp++;
if(xx==ex&&yy==ey)return stepp;
tt.x=xx, tt.y=yy,tt.step=stepp;
qu.push(tt);
}
}
}
return -1;

}

int main()
{
char ch1,ch2;
int beg,end;
while(cin>>ch1>>beg>>ch2>>end)
{
bx=ch1-'a'+1, by=beg;
ex=ch2-'a'+1, ey=end;
memset(visit,0,sizeof(visit));
visit[bx][by]=1;
int step=BFS(0);
cout<<"To get from "<<ch1<<beg<<" to "<<ch2
<<end<<" takes "<<step<<" knight moves."<<endl;

}
return 0;
}



posted @ 2011-11-25 19:25  快乐.  阅读(229)  评论(0编辑  收藏  举报