ZBLOG

A*算法C++示例

以下是一个简单的 A* 算法的 C++ 示例:

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

// 定义地图大小
const int ROWS = 5;
const int COLS = 5;

// 定义节点结构
struct Node {
    int x, y;             // 节点坐标
    int g, h;             // 路径代价g和启发式函数h值
    bool obstacle;        // 是否为障碍物
    Node* parent;         // 父节点指针

    Node(int x, int y) : x(x), y(y), g(0), h(0), obstacle(false), parent(nullptr) {}
};

// 计算两个节点之间的曼哈顿距离(启发式函数)
int manhattanDistance(Node* current, Node* goal) {
    return abs(current->x - goal->x) + abs(current->y - goal->y);
}

// 检查坐标是否在地图范围内
bool isWithinMap(int x, int y) {
    return (x >= 0 && x < ROWS && y >= 0 && y < COLS);
}

// A*算法实现
vector<Node*> astar(Node* start, Node* goal, vector<vector<Node>>& grid) {
    priority_queue<pair<int, Node*>, vector<pair<int, Node*>>, greater<pair<int, Node*>>> openList;
    vector<Node*> closedList;

    openList.push(make_pair(start->g + start->h, start));

    while (!openList.empty()) {
        auto currentNode = openList.top().second;
        openList.pop();

        if (currentNode == goal) {
            vector<Node*> path;
            while (currentNode != nullptr) {
                path.push_back(currentNode);
                currentNode = currentNode->parent;
            }
            return path;
        }

        closedList.push_back(currentNode);

        // 遍历当前节点的相邻节点
        int dx[4] = {0, 1, 0, -1};
        int dy[4] = {-1, 0, 1, 0};
        for (int i = 0; i < 4; ++i) {
            int newX = currentNode->x + dx[i];
            int newY = currentNode->y + dy[i];

            if (!isWithinMap(newX, newY))
                continue;

            auto neighbor = &grid[newX][newY];

            if (neighbor->obstacle || find(closedList.begin(), closedList.end(), neighbor) != closedList.end())
                continue;

            int newG = currentNode->g + 1;

            bool isOpen = false;
            for (auto item : openList) {
                if (item.second == neighbor) {
                    isOpen = true;
                    break;
                }
            }

            if (!isOpen || newG < neighbor->g) {
                neighbor->g = newG;
                neighbor->h = manhattanDistance(neighbor, goal);
                neighbor->parent = currentNode;

                if (!isOpen)
                    openList.push(make_pair(neighbor->g + neighbor->h, neighbor));
            }
        }
    }

    return {}; // 没有找到路径,返回空路径
}

// 打印地图和路径
void printGrid(vector<vector<Node>>& grid, const vector<Node*>& path) {
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            if (grid[i][j].obstacle)
                cout << "X ";
            else if (find(path.begin(), path.end(), &grid[i][j]) != path.end())
                cout << "* ";
            else
                cout << ". ";
        }
        cout << endl;
    }
}

int main() {
    // 初始化地图
    vector<vector<Node>> grid(ROWS, vector<Node>(COLS, Node(0, 0)));
    
    // 设置障碍物
    grid[1][1].obstacle = true;
    grid[2][1].obstacle = true;
    grid[3][1].obstacle = true;

    // 设置起点和终点
    Node* start = &grid[0][0];
    Node* goal = &grid[4][4];

    // 执行A*算法
    vector<Node*> path = astar(start, goal, grid);

    // 打印结果
    printGrid(grid, path);

    return 0;
}

这个示例实现了一个简单的 A* 算法来搜索从起点到终点的最短路径。地图由一个二维节点网格表示,其中一些节点被标记为障碍物。通过计算启发式函数(曼哈顿距离),算法可以在搜索过程中优先选择距离目标更近的路径。最后,打印出地图和找到的路径。

请注意,这只是一个基本示例,并不包含所有可能的优化和特殊情况处理。在实际应用中,您可能需要根据具体需求进行更多的改进和适应。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=13007

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?