// 定义节点结构体
struct Node {
int x, y;
int g; // 从起点到当前节点的实际距离
int h; // 从当前节点到目标节点的启发式距离
bool operator<(const Node& rhs) const {
return g + h > rhs.g + rhs.h;
}
};
// 计算启发式距离
int HeuristicItem(int x, int y, int xx, int yy)
{
return abs(x - xx) + abs(y - yy);
}
// A*寻找物品
bool AStarSearchItem(Item target, Robot& bot, int bot_id) {
priority_queue<Node> open_list;
bool closed_list[N][N] = {false};
// 用来获得路径
Node parents[N][N];
int start_x = bot.x, start_y = bot.y;
open_list.push({start_x, start_y, 0, HeuristicItem(start_x, start_y, target.x, target.y)});
while (!open_list.empty()) {
Node current = open_list.top();
open_list.pop();
if (current.x == target.x && current.y == target.y) {
// 保存路径
for (Node p = current; p.x != start_x || p.y != start_y; p = parents[p.x][p.y]) {
bot.path.push_back({p.x, p.y});
test.push_back(p.g);
}
bot.path.push_back({start_x, start_y});
reverse(bot.path.begin(), bot.path.end());
bot.current_index = 0;
bot.mbx = target.x;
bot.mby = target.y;
return true;
}
if (closed_list[current.x][current.y]) {
continue; // 已经检查过这个节点
}
closed_list[current.x][current.y] = true;
// 检查周围的节点
for (int i = 0; i < 4; i++) {
int nx = current.x + dxs[i];
int ny = current.y + dys[i];
if (nx >= 1 && nx < 201 && ny >= 1 && ny < 201 && !closed_list[nx][ny] && ch[nx][ny] != '*' && ch[nx][ny] != '#' && current.g <= 1000 ) {
open_list.push({nx, ny, current.g + 1, HeuristicItem(nx, ny, target.x, target.y)});
parents[nx][ny] = current;
}
}
}
return false;
}
照理来说,输出路径的g应该是递增的,因为g是实际距离,每次入队列都是父节点g+1,但是为什么我的输出路径g值是这样的
路径可以正常寻到,但是这个g明显不正常,是哪里出了问题