HDU1372 Knight Moves(bfs)

来源:互联网 发布:软件工程硕士就业前景 编辑:程序博客网 时间:2024/05/22 13:49





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




分析:  国际象棋的骑士同中国象棋的马    马走日    所以它以自身为中心可以向八个方向移动(和中国象棋还是略有去别的,并没有中国象棋中马有绊脚)  所以bfs最先找到的最短  




代码如下:

#include <stdio.h>#include <queue>#include <string.h>using namespace std;int map[10][10];int x1,y1,x2,y2;int dir[8][2]={{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};//   八个方向 char a[3],b[3]; struct node{int x;int y;int step;};int judge(int i,int j){if(i<0||j<0||i>=8||j>=8||map[i][j])return 0;return 1;}void bfs(){queue<node>  Q;node m,n;m.x=x1;m.y=y1;m.step=0;Q.push(m);while (!Q.empty()){n=Q.front();Q.pop();if(n.x==x2&&n.y==y2){printf ("To get from %s to %s takes %d knight moves.\n",a,b,n.step);return ;}for (int i=0;i<8;i++){node t;t.x=n.x+dir[i][0];t.y=n.y+dir[i][1];if(judge(t.x,t.y)&&!map[t.x][t.y]){map[t.x][t.y]=1;t.step=n.step+1;Q.push(t);}}}}int main (){while (scanf ("%s%s",a,b)!=EOF){x1=a[0]-'a';y1=a[1]-'0'-1;//     让坐标从0开始  x2=b[0]-'a';y2=b[1]-'0'-1; memset(map,0,sizeof(map)); map[x1][y1]=1;bfs();}return 0;} 


0 0
原创粉丝点击