volcanical 2024-03-20 12:03 采纳率: 50%
浏览 5
已结题

关于A*算法中实际路径g的问题c++


// 定义节点结构体
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值是这样的

img

路径可以正常寻到,但是这个g明显不正常,是哪里出了问题

  • 写回答

3条回答 默认 最新

  • volcanical 2024-03-20 13:27
    关注

    已经解决了,忘记了还要对已在Openlist内的节点进行判断,是否要改变父节点指向

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 3月28日
  • 已采纳回答 3月20日
  • 创建了问题 3月20日

悬赏问题

  • ¥100 nuxt、uniapp、ruoyi-vue 相关发布问题
  • ¥30 关于#测试工具#的问题:测试ai翻唱
  • ¥15 浮窗和全屏应用同时存在,全屏应用输入法无法弹出
  • ¥100 matlab2009 32位一直初始化
  • ¥15 Expected type 'str | PathLike[str]…… bytes' instead
  • ¥15 为什么在iis上部署网站,服务器可以访问,但是本地电脑访问不了
  • ¥15 三极管电路求解,已知电阻电压和三级关放大倍数
  • ¥15 ADS时域 连续相位观察方法
  • ¥15 Opencv配置出错
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。