新闻中心
C++如何实现一个简单的A*寻路算法_C++游戏AI开发中的路径规划实战
A*算法通过评估函数f=g+h结合Dijkstra的完备性和贪心搜索的高效性,在二维网格中寻最优路径;使用优先队列扩展节点,曼哈顿距离作启发函数,记录g、h、f值及父节点回溯路径,最终实现从起点到终点的完整路径规划。

在C++游戏AI开发中,A*(A星)寻路算法是路径规划的核心技术之一。它结合了Dijkstra算法的完备性和贪心搜索的高效性,通过评估函数快速找到从起点到终点的最优路径。下面用简洁的方式实现一个基础但可用的A*算法,适用于二维网格地图。
1. 定义地图与节点结构
假设地图是一个二维网格,0表示可通过,1表示障碍物。每个节点记录坐标、代价信息以及父节点用于回溯路径。
#include <vector>
#include <queue>
#include <cmath>
#include <iostream>
<p>struct Node {
int x, y;
float g, h; // g: 实际代价,h: 启发值
float f() const { return g + h; }
Node* parent;</p><pre class='brush:php;toolbar:false;'>Node(int x, int y) : x(x), y(y), g(0), h(0), parent(nullptr) {}
bool operator<(const Node& other) const {
return f() > other.f(); // 优先队列需要最小堆
}};
2. 启发函数与邻居生成
使用曼哈顿距离作为启发函数,适合四方向移动。若支持八方向,可改用对角线距离或欧几里得距离。
float heuristic(int x1, int y1, int x2, int y2) {
return abs(x1 - x2) + abs(y1 - y2); // 曼哈顿距离
}
<p>std::vector<std::pair<int, int>> getNeighbors(int x, int y) {
return {{x+1,y}, {x-1,y}, {x,y+1}, {x,y-1}};
// 若允许斜向移动,可加入 {x+1,y+1}, {x+1,y-1} 等
}</p>3. A* 核心算法实现
使用优先队列管理待处理节点,集合记录已访问位置,避免重复扩展。
星辰Agent
科大讯飞推出的智能体Agent开发平台,助力开发者快速搭建生产级智能体
378
查看详情
std::vector<Node*> aStar(const std::vector<std::vector<int>>& grid, Node* start, Node* end) { int rows = grid.size(); int cols = grid[0].size(); <pre class='brush:php;toolbar:false;'>auto isValid = [&](int x, int y) { return x >= 0 && x < rows && y >= 0 && y < cols && grid[x][y] == 0; }; std::priority_queue<Node> openList; std::vector<std::vector<bool>> closedList(rows, std::vector<bool>(cols, false)); std::vector<std::vector<Node*>> nodeMap(rows, std::vector<Node*>(cols, nullptr)); for (int i = 0; i < rows; ++i) for (int j = 0; j < cols; ++j) if (grid[i][j] == 0) nodeMap[i][j] = new Node(i, j); start = nodeMap[start->x][start->y]; end = nodeMap[end->x][end->y]; start->h = heuristic(start->x, start->y, end->x, end->y); openList.push(*start); while (!openList.empty()) { Node current = openList.top(); openList.pop(); if (closedList[current.x][current.y]) continue; closedList[current.x][current.y] = true; if (current.x == end->x && current.y == end->y) { // 回溯路径 std::vector<Node*> path; Node* p = end; while (p != nullptr) { path.push_back(p); p = p->parent; } return path; } for (auto& [nx, ny] : getNeighbors(current.x, current.y)) { if (!isValid(nx, ny) || closedList[nx][ny]) continue; Node* neighbor = nodeMap[nx][ny]; float tentativeG = current.g + 1; // 假设每步代价为1 if (tentativeG < neighbor->g || !closedList[nx][ny]) { neighbor->parent = &const_cast<Node&>(current); neighbor->g = tentativeG; neighbor->h = heuristic(nx, ny, end->x, end->y); openList.push(*neighbor); } } } return {}; // 无路径
}
4. 使用示例与清理资源
演示如何调用并输出结果。注意实际项目中建议使用智能指针或对象池管理内存。
int main() {
std::vector<std::vector<int>> grid = {
{0, 0, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 0, 0, 0},
{0, 0, 0, 1, 0},
{0, 0, 0, 0, 0}
};
<pre class='brush:php;toolbar:false;'>Node* start = new Node(0, 0);
Node* end = new Node(4, 4);
auto path = aStar(grid, start, end);
if (!path.empty()) {
std::cout << "Found path:\n";
for (auto it = path.rbegin(); it != path.rend(); ++it) {
std::cout << "(" << (*it)->x << "," << (*it)->y << ") ";
}
std::cout << "\n";
} else {
std::cout << "No path found.\n";
}
// 简单释放(实际应遍历所有创建的节点)
for (auto& row : grid)
for (auto val : row)
if (val == 0) /* 伪代码 */ delete /* 对应节点 */;
delete start; delete end;
return 0;}
基本上就这些。这个实现虽然简单,但展示了A*在C++中的核心逻辑:代价评估、优先扩展、路径回溯。在真实游戏中,你可以进一步优化数据结构(如使用索引代替指针)、支持动态障碍、多单位协同避让等。不复杂但容易忽略细节,比如防止重复入队和正确更新g值。掌握基础后,扩展性强。
以上就是C++如何实现一个简单的A*寻路算法_C++游戏AI开发中的路径规划实战的详细内容,更多请关注其它相关文章!
# 面向对象
# seo企业站运营计划
# 宜宾营销推广多少钱一个月
# 河北seo服务电话号码
# 谷歌seo 优化-蓝颜SEO
# 贵阳倾注seo新浪博客
# 妇产科seo
# 手表seo
# 茶酒生鲜的网络营销推广方案
# 佛山网站建设邓先生
# 东莞关键词排名查询
# 是一个
# 欧几里得
# c++
# 点到
# 最优
# 有什么区别
# 如何使用
# 如何实现
# 数据结构
# 曼哈顿
# stream
# ios
# ai
# node
# a*寻路
相关栏目:
【
科技资讯46185 】
【
网络学院92790 】
相关推荐:
4399免费游戏网址入口 4399小游戏免费入口点开即玩
《刺客信条:影》PS5 Pro和Switch 2画面对比
HTML空白字符处理机制:渲染、DOM与编码实践
处理嵌套交互式控件:前端可访问性指南
在VS Code中配置和运行Dart程序的完整步骤
J*a 递归快速排序中静态变量的状态管理与陷阱
微博网页版首页入口 微博电脑端官网登录链接
淘宝支付提示失败如何解决 淘宝支付流程优化方法
Win11怎么查看显卡显存 Win11显示适配器属性及专用视频内存查询
聚水潭ERP登录页面入口 聚水潭ERP官网登录界面
如何使用Go和Martini动态服务解码后的图片
Go语言中Map值调用指针接收器方法的限制与应对
Excel Power Pivot如何处理XML数据源 构建高级数据模型
windows10怎么关闭系统提示音_windows10彻底静音设置方法
如何在网页中实现特定地点的随机图片展示
Tailwind CSS line-clamp 布局问题解析与修复指南
实现全屏滚动与导航点:专业教程
KFC游戏互动怎么赢取优惠券_KFC线上游戏活动参与与优惠代码赢取教程
Lar*el头像管理:图片缩放与旧文件删除的最佳实践
特斯拉自动驾驶房车计划曝光 原型车将于2027年亮相
探索高级语言到原生C/C++的转译:挑战与内存管理策略
composer 和 npm/yarn 在管理依赖方面有什么核心思想差异?
深入理解Promise链:如何在catch后中断then的执行
移动端XML文件怎么转换成Excel 手机和平板上的解决方案
MAC怎么安装Homebrew包管理器_MAC为开发者和高级用户安装命令行工具
163邮箱注册官网 免费申请163个人邮箱
解决Bootstrap卡片顶部边距导致背景图下移的问题
Yandex官网搜索引擎免登录_俄罗斯Yandex一键直达入口
Windows 11怎么彻底关闭定位_Windows 11服务中禁用Geolocation
荣耀Play7T运行卡顿解决_荣耀Play7T性能优化
抖音小游戏合成大西瓜免费秒玩入口链接 抖音小游戏热门合集秒玩网站
QQ邮箱官方邮箱登录入口 QQ邮箱网页版快速访问
深入理解J*aScript中的B样条曲线与节点向量生成
单射、满射与双射的关系 一文理清所有逻辑
uc浏览器网页版极速入口 uc网页浏览器网页版流畅体验
PHP中高效并行检查多链接状态的教程
Excel函数批量查找替换超快方法_Excel用REPLACE和FIND函数秒级替换
NetBeans Ant项目:自动化将资源文件复制到dist目录的教程
谷歌浏览器最新官方入口链接 谷歌浏览器网页版官网导航
Golang如何优化CPU绑定任务分配策略_Golang CPU任务分配优化实践
J*aScript设计模式实践_j*ascript代码优化
C++如何检测键盘输入_C++ _kbhit与_getch函数非阻塞输入
Yandex免登录网页版地址 Yandex搜索引擎官方访问入口
内存检查:在VS Code中调试C++时的内存视图
css滚动区域卡顿如何改善_css滚动问题用will-change优化渲染
c++如何使用TBB库进行任务并行_c++ Intel线程构建模块
解决Flask中Quill编辑器内容提交失败及TypeError的指南
漫蛙2正版漫画站 漫蛙2网页版快速访问入口
Adobe PDF表单中利用J*aScript解析与格式化日期组件的教程
Fabric模组开发:自定义物品与物品组的现代管理方法


2025-12-05
浏览次数:次
返回列表
or<int>>& grid,
Node* start, Node* end) {
int rows = grid.size();
int cols = grid[0].size();
<pre class='brush:php;toolbar:false;'>auto isValid = [&](int x, int y) {
return x >= 0 && x < rows && y >= 0 && y < cols && grid[x][y] == 0;
};
std::priority_queue<Node> openList;
std::vector<std::vector<bool>> closedList(rows, std::vector<bool>(cols, false));
std::vector<std::vector<Node*>> nodeMap(rows, std::vector<Node*>(cols, nullptr));
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
if (grid[i][j] == 0)
nodeMap[i][j] = new Node(i, j);
start = nodeMap[start->x][start->y];
end = nodeMap[end->x][end->y];
start->h = heuristic(start->x, start->y, end->x, end->y);
openList.push(*start);
while (!openList.empty()) {
Node current = openList.top(); openList.pop();
if (closedList[current.x][current.y]) continue;
closedList[current.x][current.y] = true;
if (current.x == end->x && current.y == end->y) {
// 回溯路径
std::vector<Node*> path;
Node* p = end;
while (p != nullptr) {
path.push_back(p);
p = p->parent;
}
return path;
}
for (auto& [nx, ny] : getNeighbors(current.x, current.y)) {
if (!isValid(nx, ny) || closedList[nx][ny]) continue;
Node* neighbor = nodeMap[nx][ny];
float tentativeG = current.g + 1; // 假设每步代价为1
if (tentativeG < neighbor->g || !closedList[nx][ny]) {
neighbor->parent = &const_cast<Node&>(current);
neighbor->g = tentativeG;
neighbor->h = heuristic(nx, ny, end->x, end->y);
openList.push(*neighbor);
}
}
}
return {}; // 无路径