HDU 1372Knight Moves(简单的BFS)
发布时间: 2013-09-08 15:21:21 作者: rapoo
HDU 1372Knight Moves(简单的BFS)
e2 e4a1 b2b2 c3a1 h8a1 h7h8 a1b1 c3f6 f6
To get from e2 to e4 takes 2 knight moves.To get from a1 to b2 takes 4 knight moves.To get from b2 to c3 takes 2 knight moves.To get from a1 to h8 takes 6 knight moves.To get from a1 to h7 takes 5 knight moves.To get from h8 to a1 takes 6 knight moves.To get from b1 to c3 takes 1 knight moves.To get from f6 to f6 takes 0 knight moves.
#include<iostream>#include<cstring>#include<cmath>#include<queue>#include<cstdio>using namespace std;char a[10];struct node{ int x; int y;};node sta,en; //sta为起点,en为终点int visi[10][10]; //查看某点有无被访问过int res[10][10]; //记录每个点的步数int dir[8][2]= //八个方向{ {-2,-1},{2,-1},{-2,1},{2,1}, {-1,-2},{1,-2},{-1,2},{1,2}};queue <int>q;void bfs(){ memset(visi,0,sizeof(visi)); memset(res,100,sizeof(res)); while(!q.empty()) //将队清空 q.pop(); int i; q.push(sta.x*8+sta.y); //将起点入队 visi[sta.x][sta.y]=1; res[sta.x][sta.y]=0; while(!q.empty()) { int tmp=q.front(); q.pop(); int cx=tmp/8; //再转换成坐标 int cy=tmp%8; //current的x,y if(cx==en.x&&cy==en.y) return; for(i=0;i<8;i++) { int px,py; px=cx+dir[i][0],py=cy+dir[i][1]; if(!visi[px][py]&&px>=0&&px<8&&py>=0&&py<8) //防止越界 { res[px][py]=res[cx][cy]+1; //比上次多一步 visi[px][py]=1; q.push(px*8+py); } } }}int main(){ while(gets(a)) { sta.x=a[0]-'a'; //转化为坐标 sta.y=a[1]-'1'; en.x=a[3]-'a'; en.y=a[4]-'1'; bfs(); //cout<<sta.x<<" "<<sta.y<<endl; //cout<<en.x<<" "<<en.y<<endl; printf("To get from %c%c to %c%c takes %d knight moves.\n",a[0],a[1],a[3],a[4],res[en.x][en.y]); } return 0;}//31MS 240K/*e2 e4a1 b2b2 c3a1 h8a1 h7h8 a1b1 c3f6 f6*/