2013寒假练习 1030:Knight Moves

来源:互联网 发布:最幸福的人网络歌手 编辑:程序博客网 时间:2024/06/16 10:06

地址:http://acm.bit.edu.cn/mod/programming/view.php?id=681

给定起点和终点,问马从起点跳到终点所需最少步数。直接BFS无须多言。。

#include<iostream>#include<queue>using namespace std;bool flag[8][8];int dir[8][2]={{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};struct node{char x;int y;int t;}op,ed,now,next;int main()      //bfs{while(~scanf("%c%d%*c%c%d",&op.x,&op.y,&ed.x,&ed.y)){op.t=0;memset(flag,0,sizeof(flag));queue<struct node>q;q.push(op);while(!q.empty())  {now=q.front();if(now.x==ed.x&&now.y==ed.y){printf("To get from %c%d to %c%d takes %d knight moves.\n",op.x,op.y,ed.x,ed.y,now.t);break;}for(int i=0;i<8;i++){next.x=now.x+dir[i][0],next.y=now.y+dir[i][1],next.t=now.t+1;if(next.x>='a'&&next.x<='h'&&next.y>=1&&next.y<=8&&!flag[next.x-'a'][next.y-1]){flag[next.x-'a'][next.y-1]=1;q.push(next);}}q.pop();}}return 0;}



 

 

原创粉丝点击