HDU 1372 Knight Moves(bfs)

Description
一个8*8的棋盘,用a~h表示1~8列,用1~8表示1~8行,给出起点和终点,问马最少需要跳几步才能从起点到达终点
Input
多组用例,每组用例包含两个长度为2的字符串分别表示起点和终点,以文件尾结束输入
Output
对于每组用例,输出马从起点到终点最少需要跳几步
Sample Input
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
Sample Output
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.
Solution
简单bfs
Code

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
#define maxn 11111
struct node
{
    int x,y,step;
};
int dx[]={-2,-2,-1,-1,1,1,2,2};
int dy[]={-1,1,-2,2,-2,2,-1,1};
int sx,sy,ex,ey,vis[9][9];
int bfs()
{
    queue<node>que;
    memset(vis,0,sizeof(vis));
    node now,temp;
    temp.x=sx,temp.y=sy,temp.step=0;
    que.push(temp);
    vis[sx][sy]=1;
    while(!que.empty())
    {
        now=que.front();que.pop();
        if(now.x==ex&&now.y==ey)return now.step;
        for(int i=0;i<8;i++)
        {
            int xx=now.x+dx[i],yy=now.y+dy[i];
            if(xx<0||xx>7||yy<0||yy>7||vis[xx][yy])continue;
            temp.x=xx,temp.y=yy,temp.step=now.step+1;
            que.push(temp);
            vis[xx][yy]=1;
        }
    }
}
int main()
{
    char a[3],b[3];
    while(~scanf("%s %s",a,b))
    {
        sx=a[0]-'a',sy=a[1]-'1';
        ex=b[0]-'a',ey=b[1]-'1';
        int ans=bfs();
        printf("To get from %s to %s takes %d knight moves.\n",a,b,ans);
    }
    return 0;
}

你可能感兴趣的:(HDU 1372 Knight Moves(bfs))