什么是A-Star算法
A*(A-Star)算法是一种静态路网中求解最短路最有效的方法。这是一种在图形平面上,有多个节点的路径,求出最低通过成本的算法。该算法的成本计算公式表示为:
f(n)=g(n)+h(n)f(n)=g(n)+h(n)f(n)=g(n)+h(n)
其中,f(n)f(n)f(n)是节点nnn从初始点到目标点的估价函数,g(n)g(n)g(n)是在状态空间中从初始节点到nnn节点的实际代价,h(n)h(n)h(n)是从nnn到目标节点最佳路径的估计代价。
一般情况下,g(n)g(n)g(n)是从起点到当前节点nnn的移动量。相邻节点间水平或垂直方向的移动量一边为1,对角线方向的移动量则为1.4(勾股定理);h(n)h(n)h(n)则是从当前节点nnn到终点的移动量的估算值,一般采用“曼哈顿距离”。
路径规划问题,则可以将搜索区域简化为二维数组,二维数组中的每一个元素都表示网格中的一个节点,节点则被标记为可以通过或不可以通过,则最终的路径就是从起点到终点的节点的集合。
算法流程
C++代码实现
AStar类定义文件,AStar.h
#pragma once
#include <vector>
#include <list>
struct Point
{
int x,y;
int F,G,H;
Point *parent;
Point(int _x,int _y):x(_x),y(_y),F(0),G(0),H(0),parent(nullptr) {
}
};
class AStar {
public:
AStar();
void InitAStar(std::vector<std::vector<int>> &_maze);
std::list<Point *> GetPath(Point &startPoint, Point &endPoint, bool isIgnoreCorner);
private:
Point *FindPath(Point &startPoint, Point &endPoint, bool isIgnoreCorner);
std::vector<Point *> GetSurroundPoints(const Point *point, bool isIgnoreCorner) const;
bool IsReachable(const Point *point, const Point *target, bool isIgnoreCorner) const;
Point *IsInList(const std::list<Point *> &list, const Point *point) const