hdu1372 Knight Moves

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

题意:给出骑士的骑士位置和目标位置,计算骑士要走多少步

思路:首先要做这道题必须要理解国际象棋中骑士的走法,国际象棋中,骑士是在一个3*2的格子中进行对角线移动,通过画图很容易就知道骑士最多可以朝八个方向移动,那么就朝8个方向进行BFS即可

感想:

这是我的第一道象棋题目啊,我不会下象棋大哭

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
int step;
int to[8][2] = {{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};//骑士移动的8个方位
int map[10][10],ex,ey;
char s1[5],s2[5];
struct node  //定义一个类
{
    int x,y,step;
};
int check(int x,int y)
{
    if(x<0 || y<0 || x>=8 || y>=8 || map[x][y])
    return 1;
    return 0;
}
int bfs()
{
    int i;
    queue<node> Q;
    node p,next,q;    //定义3个对象
    p.x = s1[0]-'a';  //开始
    p.y = s1[1]-'1';
    p.step = 0;       //初始化走了0步
    ex = s2[0]-'a';   //后来
    ey = s2[1]-'1';
    memset(map,0,sizeof(map));
    map[p.x][p.y] = 1;
    Q.push(p);        //添加到队列中
    while(!Q.empty())  //当队列不为空的时候才能执行这一步
    {
        q = Q.front();  //从队列中拿出队头出来
        Q.pop();        //去除队头
        if(q.x == ex && q.y == ey)
        return q.step;
        for(i = 0;i<8;i++)
        {
            next.x = q.x+to[i][0];
            next.y = q.y+to[i][1];
            if(next.x == ex && next.y == ey)
            return q.step+1;
            if(check(next.x,next.y))
            continue;
            next.step = q.step+1;//满足条件加1
            map[next.x][next.y] = 1;
            Q.push(next);  //又添加到队列中
        }
    }
    return 0;
}
int main()
{
    while(~scanf("%s %s",s1,s2))
    {
        printf("To get from %s to %s takes %d knight moves.\n",s1,s2,bfs());
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值