Adament Cabin

  • 计算机
    • Algorithm
    • Linux
    • Problems
    • AI
  • 日语学习
  • ACG
    • 追番列表
    • 游戏
  • 常日说
  • 杂物
    • 资料
    • 资源
    • 治疗中心
  • ao的链接
  • 分站
  • Chinese
    • Japanese
Adament Cabin
恋厨综合症第二治疗中心
  1. 首页
  2. 计算机
  3. Algorithm
  4. 正文

A*搜索算法

2021年11月4日 1895点热度 0人点赞 0条评论

A*搜索算法(A* search algorithm)是一种在图形平面上,有多个节点的路径,求出最低通过成本的算法。

A*不是贪心算法。

A*很好用,不难学,简单易懂。通常用于游戏NPC寻路。(啊?

该算法综合了最良优先搜索和Dijkstra算法的优点:在进行启发式搜索提高算法效率的同时,可以保证找到一条最优路径。

A*搜索算法很像隔壁的广度优先,区别在于广度有限是无脑向4个方向拓展,而A*只向着代价(cost)最低的方向拓展。

代价为当前步数+曼哈顿距离。(为什么请找高数dalao,我也不会www)

据说步数也可以是当前步数+正常的距离(sqrt(x^2-y^2))

#include <iostream>
#include <cmath>
#include <queue>
using namespace std;
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int m[100][100], v[100][100];
int cost[5];
struct road{
    int x;
    int y;
    int step;
    int cost;
};
queue<road> ma;
int Manhaton(int x1, int y1, int x2, int y2){
    return abs(x1 - x2) + abs(y1 - y2);
}
int main(){
    int a, b;
    cin >> a >> b;
    int nu;
    for (int i = 1; i <= a; i++)
        for (int j = 1; j <= b; j++){
            cin >> nu;
            m[i][j] = nu + 1;
        }
    int startx, starty, endx, endy;
    cin >> startx >> starty >> endx >> endy;
    road start;
    start.x = startx;
    start.y = starty;
    start.step = 0;
    ma.push(start);
    v[startx][starty] = 1;
    bool flag = 0;
    while (!ma.empty()){
        road next[4];
        start = ma.front();
        if (start.x == endx && start.y == endy){
            cout << start.step << endl;
            flag = 1;
            break;
        }
        for (int k = 0; k < 4; k++){
            next[k].x = start.x + dx[k];
            next[k].y = start.y + dy[k];
            next[k].step = start.step + 1;
            next[k].cost = next[k].step + Manhaton(next[k].x, next[k].y, endx, endy);
        }
        int mincost = 999999;
        int mink = 9;
        for (int ff = 0; ff < 4; ff++){
            if (m[next[ff].x][next[ff].y] == 1 && v[next[ff].x][next[ff].y] == 0)
            {
                mincost = min(mincost, next[ff].cost);
                if (mincost == next[ff].cost)
                    mink = ff;
                v[next[ff].x][next[ff].y] = 1;
            }
        }
        if (mincost != 999999 || mink != 9)
            ma.push(next[mink]);
        ma.pop();
    }
    if (flag == 0)
        cout << "Not Found" << endl;
    return 0;
}
标签: C/C++/C#
最后更新:2022年4月21日

BiyiAdopac

是铁龙鸣。

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

分类
  • AI / 1篇
  • Algorithm / 5篇
  • Linux / 6篇
  • Problems / 3篇
  • 常日说 / 1篇
  • 日本語 / 2篇
  • 游戏 / 1篇
  • 计算机 / 14篇
  • 资料 / 4篇
标签聚合
AI Magisk LaTex Physics C/C++/C# Learning Arcaea ArchLinux
The World of Scarlet
https://www.adament.xyz/wp-content/uploads/2024/10/the-world-of-scarlet-Piano.mp3

COPYRIGHT © 2025 adament.xyz. ALL RIGHTS RESERVED.
本站虽然不重要但是还是有的 隐私政策