A*搜索需要decrease-key操作吗?
创始人
2024-07-21 11:40:43
0

需要。

在 A* 算法中,为了保证估价函数能够最优地引导搜索,需要对 open 队列中的节点按照估价函数的值进行排序。但是,每次更新一个节点的估价函数值后,必须对这个节点在 open 队列中的位置进行调整。这个操作就是 decrease-key 操作。

下面是动态数组实现的 A* 搜索算法:

import heapq

def a_star(start, goal, h_func, neighbors_func):
    # initialization
    open_list = [(h_func(start), start)] # sorted by h_func
    came_from = {}
    cost_so_far = {}
    came_from[start] = None
    cost_so_far[start] = 0

    while len(open_list) > 0:
        # remove and return the node with the lowest f = g + h
        current = heapq.heappop(open_list)[1]

        if current == goal:
            # goal reached
            break

        # expand neighbors
        for neighbor in neighbors_func(current):
            new_cost = cost_so_far[current] + 1 # assuming edge cost = 1
            if neighbor not in cost_so_far or new_cost < cost_so_far[neighbor]:
                # update or add neighbor to open list
                cost_so_far[neighbor] = new_cost
                priority = new_cost + h_func(neighbor)
                heapq.heappush(open_list, (priority, neighbor))
                came_from[neighbor] = current

    return came_from, cost_so_far

在上面的代码中,open_list 是用堆实现的优先队列,每个元素是一个二元组 (priority, node),其中 priority 是节点的 f 值,node 是节点本身。h_func 是估价函数,neighbors_func 是邻居生成函数,返回值是当前节点的邻居列表。

值得注意的是,在堆中插入一个元素的时间复杂度为 O(log n),而更新堆中一个元素的时间复杂度为 O(n),其中 n 是

相关内容

热门资讯

安装了Anaconda之后找不... 在安装Anaconda后,如果找不到Jupyter Notebook,可以尝试以下解决方法:检查环境...
安装安卓应用时出现“Play ... 在安装安卓应用时出现“Play Protect 警告弹窗”的原因是Google Play Prote...
安卓系统怎么连不上carlif... 安卓系统无法连接CarLife的原因及解决方法随着智能手机的普及,CarLife这一车载互联功能为驾...
iwatch怎么连接安卓系统,... 你有没有想过,那款时尚又实用的iWatch,竟然只能和iPhone好上好?别急,今天就来给你揭秘,怎...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
iqoo安卓14系统怎么升级系... 亲爱的iQOO手机用户们,是不是觉得你的手机系统有点儿落伍了呢?别急,今天就来手把手教你如何升级到最...
vivo安卓系统取消更新系统,... 亲爱的vivo手机用户们,你们是不是也遇到了这样的烦恼:手机里突然冒出一个更新提示,点开一看,哇,新...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安卓系统连接荣耀手表,操作指南... 亲爱的手机控们,是不是最近入手了一款酷炫的荣耀手表,却不知道怎么和安卓手机完美“牵手”呢?别急,今天...