POJ 2243 Knight Moves(A*算法)

本文介绍使用A*算法解决骑士行走问题的方法。通过定义合适的g函数和启发函数h,利用优先队列进行节点排序,实现从起点到终点的最短路径搜索。代码中详细展示了A*算法的具体实现。

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

本题题意非常简单,就是给你一个起点和一个终点,按骑士的走法,从起点到终点的最少移动多少次。

可以采用双向广搜或者A*算法来解决,这里博主选择了采用A*算法来解决。

其中g函数为走到当前状态的经过的步数,启发函数h为当前点到终点的曼哈顿距离,用优先队列保存每个状态按照g+h排序

代码如下

#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
using namespace std;

struct Knight
{
    int x, y, step;
    int g, h, f;
    bool operator <(const Knight &k)const
    {
        return f > k.f;
    }
};

bool vis[8][8];
int sx, ex, sy, ey, ans;
int dirs[8][2] = { { -2,-1 },{ -2,1 },{ 2,-1 },{ 2,1 },{ -1,-2 },{ -1,2 },{ 1,-2 },{ 1,2 } };
priority_queue<Knight> pq;

bool in_map(Knight a)
{
    if (a.x < 0 || a.y < 0 || a.x >= 8 || a.y >= 8)
        return false;
    return true;
}

int get_h(Knight a)
{
    return (abs(a.x - ex) + abs(a.y - ey));
}

void Astar()
{
    Knight t, s;
    while (!pq.empty())
    {
        t = pq.top();
        pq.pop();
        vis[t.x][t.y] = true;
        if (t.x == ex&&t.y == ey)
        {
            ans = t.step;
            return;
        }
        for (int i = 0;i < 8;i++)
        {
            s.x = t.x + dirs[i][0];
            s.y = t.y + dirs[i][1];
            if (in_map(s) && !vis[s.x][s.y])
            {
                s.g = t.g + 3;//3表示根号5向上取整
                s.h = get_h(s);
                s.f = s.g + s.h;
                s.step = t.step + 1;
                pq.push(s);
            }
        }
    }
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);
    char a, b;
    while (~scanf("%c%d %c%d", &a, &sy, &b, &ey))
    {
        getchar();
        sx = (a - 'a');
        ex = (b - 'a');
        sy--;
        ey--;
        memset(vis, false, sizeof(vis));
        Knight k;
        k.x = sx;
        k.y = sy;
        k.g = k.step = 0;
        k.h = get_h(k);
        k.f = k.g + k.h;
        while (!pq.empty()) pq.pop();
        pq.push(k);
        Astar();
        printf("To get from %c%d to %c%d takes %d knight moves.\n", a, sy+1, b, ey+1, ans);
    }
    return 0;
}

另外给大家推荐一个讲解的A*博客,也是我在学习A*的时候看的博客,希望对大家有所帮助:
http://www.cppblog.com/mythit/archive/2009/04/19/80492.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值