HDU 1372 Knight Moves(bfs)

本文介绍了一个简单的广度优先搜索(BFS)算法来解决8*8棋盘上马从起点到终点的最少移动次数问题。通过使用C++实现并展示了一段简洁高效的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值