A*算法详解

A*算法讲解

一、A*算法基本概念

A*(A-Star)算法是一种启发式搜索算法,广泛应用于路径规划和图遍历问题。它结合了两种搜索算法的优点:

  • Dijkstra算法的完备性和最优性
  • 贪心最佳优先搜索(Greedy Best-First Search)的效率和启发性

A*算法的核心思想是:在搜索过程中,通过评估函数f(n)来选择最有希望的节点进行扩展,从而找到从起点到目标点的最短路径。

二、A*算法的核心公式

A*算法的核心在于其评估函数:

f(n) = g(n) + h(n)

其中:

  • f(n) 是节点n的估价函数
  • g(n) 是从起点到节点n的实际代价
  • h(n) 是从节点n到目标节点的估计代价(启发式函数)

三、A*算法的详细步骤

  1. 初始化两个集合:开放列表(OpenList)和关闭列表(ClosedList)
  2. 将起点加入OpenList
  3. 当OpenList不为空时,重复以下步骤:
    • 从OpenList中选取f值最小的节点作为当前节点
    • 如果当前节点是目标节点,则找到路径,算法结束
    • 否则,将当前节点从OpenList移到ClosedList
    • 对当前节点的每个相邻节点:
      • 如果该节点在ClosedList中,忽略它
      • 如果该节点不在OpenList中,计算其f值并加入OpenList
      • 如果该节点已经在OpenList中,检查新路径是否更优,如果是则更新其信息
  4. 如果OpenList为空,则无法找到路径

四、C++代码实现示例

以下是一个简化的A*算法实现,用于在二维网格中找到最短路径:

#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <cmath>
#include <algorithm>
using namespace std;

// 定义网格点结构
struct Point {
    int x, y;
    
    bool operator==(const Point& other) const {
        return x == other.x && y == other.y;
    }
};

// 哈希函数,用于unordered_map
struct PointHash {
    size_t operator()(const Point& p) const {
        return hash<int>()(p.x) ^ hash<int>()(p.y);
    }
};

// 节点信息
struct Node {
    Point pos;      // 位置
    int g;          // 从起点到该点的实际代价
    int h;          // 该点到终点的启发式估计
    Point parent;   // 父节点
    
    int f() const { return g + h; }  // 估价函数
};

// 计算两点间的曼哈顿距离(启发式函数)
int heuristic(const Point& a, const Point& b) {
    return abs(a.x - b.x) + abs(a.y - b.y);
}

// A*算法主函数
vector<Point> astar(vector<vector<int>>& grid, Point start, Point goal) {
    int rows = grid.size();
    int cols = grid[0].size();
    
    // 方向数组:上、右、下、左
    vector<pair<int, int>> dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    
    // 使用优先队列(小顶堆)作为开放列表
    auto cmp = [](const Node& a, const Node& b) { return a.f() > b.f(); };
    priority_queue<Node, vector<Node>, decltype(cmp)> openList(cmp);
    
    // 已访问节点集合
    unordered_map<Point, Point, PointHash> cameFrom;
    
    // 记录各点的g值
    unordered_map<Point, int, PointHash> gScore;
    
    // 初始化起点
    openList.push({start, 0, heuristic(start, goal), {-1, -1}});
    gScore[start] = 0;
    
    while (!openList.empty()) {
        Node current = openList.top();
        openList.pop();
        
        // 如果到达目标
        if (current.pos == goal) {
            // 重建路径
            vector<Point> path;
            Point curr = current.pos;
            while (!(curr.x == -1 && curr.y == -1)) {
                path.push_back(curr);
                curr = cameFrom[curr];
            }
            reverse(path.begin(), path.end());
            return path;
        }
        
        // 遍历相邻节点
        for (auto& dir : dirs) {
            Point next = {current.pos.x + dir.first, current.pos.y + dir.second};
            
            // 检查边界和障碍物
            if (next.x < 0 || next.x >= rows || next.y < 0 || next.y >= cols || grid[next.x][next.y] == 1)
                continue;
            
            int tentative_g = gScore[current.pos] + 1;
            
            if (gScore.find(next) == gScore.end() || tentative_g < gScore[next]) {
                // 发现更好的路径
                cameFrom[next] = current.pos;
                gScore[next] = tentative_g;
                openList.push({next, tentative_g, heuristic(next, goal), current.pos});
            }
        }
    }
    
    // 没有找到路径
    return {};
}

// 打印网格和路径
void printPath(vector<vector<int>>& grid, const vector<Point>& path) {
    vector<vector<char>> display = vector<vector<char>>(grid.size(), vector<char>(grid[0].size(), ' '));
    
    // 填充网格
    for (int i = 0; i < grid.size(); i++) {
        for (int j = 0; j < grid[0].size(); j++) {
            if (grid[i][j] == 1)
                display[i][j] = '#';  // 障碍物
            else
                display[i][j] = '.';  // 空地
        }
    }
    
    // 标记路径
    for (const auto& p : path) {
        display[p.x][p.y] = '*';
    }
    
    // 标记起点和终点
    if (!path.empty()) {
        display[path.front().x][path.front().y] = 'S';  // 起点
        display[path.back().x][path.back().y] = 'G';    // 终点
    }
    
    // 打印
    for (const auto& row : display) {
        for (char cell : row) {
            cout << cell << ' ';
        }
        cout << endl;
    }
}

int main() {
    // 创建示例网格(0表示可通行,1表示障碍物)
    vector<vector<int>> grid = {
        {0, 0, 0, 0, 0},
        {0, 1, 1, 0, 0},
        {0, 0, 1, 0, 0},
        {0, 0, 1, 1, 0},
        {0, 0, 0, 0, 0}
    };
    
    Point start = {0, 0};
    Point goal = {4, 4};
    
    vector<Point> path = astar(grid, start, goal);
    
    if (path.empty()) {
        cout << "无法找到路径!" << endl;
    } else {
        cout << "找到路径!长度:" << path.size() << endl;
        printPath(grid, path);
    }
    
    return 0;
}

五、A*算法的数据结构解析

1. 开放列表(OpenList)

  • 实现:优先队列(小顶堆)
  • 作用:存储待探索的节点,按f值排序
  • 复杂度:插入和删除最小元素的时间复杂度为O(log n)

2. 关闭列表(ClosedList)

  • 实现:哈希表(unordered_map)
  • 作用:存储已经探索过的节点
  • 复杂度:查找、插入和删除的平均时间复杂度为O(1)

六、启发式函数的选择

启发式函数h(n)的选择对A*算法的效率至关重要:

  1. 曼哈顿距离:适用于四方向移动的网格

    h(n) = |n.x - goal.x| + |n.y - goal.y|
    
  2. 欧几里得距离:适用于任意方向移动

    h(n) = sqrt((n.x - goal.x)² + (n.y - goal.y)²)
    
  3. 切比雪夫距离:适用于八方向移动的网格

    h(n) = max(|n.x - goal.x|, |n.y - goal.y|)
    

七、A*算法的特性

  • 完备性:如果存在解,A*一定能找到
  • 最优性:当h(n)不高估实际代价时,A*能找到最优解
  • 时间复杂度:O(b^d),其中b是分支因子,d是解的深度
  • 空间复杂度:O(b^d),需要存储所有生成的节点

八、相关和进阶算法

  1. Dijkstra算法:A的特例,当h(n)=0时,A退化为Dijkstra
  2. 贪心最佳优先搜索:当g(n)=0时,A*退化为贪心最佳优先搜索
  3. 双向A*:从起点和终点同时开始搜索,提高效率
  4. IDA(迭代加深A)**:结合迭代加深和A*,降低空间复杂度
  5. D Lite*:适用于动态环境中的路径规划
  6. Jump Point Search:A*的优化变体,在网格地图上跳过冗余节点
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值