广度搜索hdu1372

题意大概就是在国际象棋上,问马从a点到b点需要的最短步数。马的走法和中国象棋的类似。

思路:这种求最少步数或者最小次数的题一般都是用广度搜索来解就行了。

#include <iostream>
using namespace std;
#include <queue>
#include <string.h>
int s1, s2, e1, e2;
int map[8][8];
int x2x[8] = {1, 2, 1, 2, -1, -2, -1, -2}; //把可以走的方向用数组记录下来
int y2y[8] = {2, 1, -2, -1, 2, 1, -2, -1};
int bfs()
{
    int x1, y1, x2, y2;
    memset(map, 0, sizeof(map));
    queue<int>q;
    q.push(s1);
    q.push(s2);
    while(!q.empty())
    {
        x1 = q.front();
        q.pop();
        y1 = q.front();
        q.pop();
        if(x1 == e1 && y1 == e2)  //达到终点了就直接return步数
        {
            return map[x1][y1];
        }
        for(int i = 0; i < 8; i++)
        {
            x2 = x1 + x2x[i];
            y2 = y1 + y2y[i];
            if(x2 < 0 || x2 > 7 || y2 < 0 || y2 > 7 || map[x2][y2]>0)  //如果走的下一步不在图中直接continue
            {
                continue;
            }
            map[x2][y2] = map[x1][y1] + 1; //步数加1
            q.push(x2);
            q.push(y2);
        }
    }
    return 0;
}
int main()
{
    char a[3], b[3];
    while(cin>>a>>b)
    {
        s1 = a[0] - 'a'; //行数
        s2 = a[1] - '1'; //列数
        e1 = b[0] - 'a'; //行数
        e2 = b[1] - '1'; //列数
        int total = bfs();
        cout<<"To get from "<<a<<" to "<<b<<" takes "<<total<<" knight moves."<<endl;

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值