A*算法是一种常用的寻路算法,其运用了启发式搜索的思想,可以在有向无环图(DAG)上找到最短路径。其中,扩展节点的顺序对于算法的效率和正确性都有很大影响。

  1. 根据估价函数排序

A*算法的核心在于估价函数,该函数用来评估从起点到当前节点的代价。在扩展节点时,我们可以根据节点的估价函数值从小到大排序,以保证首先扩展的是“最有可能”存在最短路径的节点。具体代码如下:

function a_star(graph, start, end, heuristic): // 初始化起点和终点的估价函数值 start.h_cost = heuristic(start, end) end.h_cost = 0

// 初始化起点的代价值
start.g_cost = 0

// 用最小堆来维护待扩展的优先级队列
open_list = new PriorityQueue()
open_list.push(start)

// 双向链表来记录已经扩展过的节点
closed_list = new DoublyLinkedList()

while not open_list.empty():
    // 弹出估价函数值最小的节点
    current_node = open_list.pop()

    // 如果当前节点已经扩展过了,跳过
    if current_node in closed_list:
        continue

    // 如果当前节点为终点,返回路径
    if current_node == end:
        return construct_path(current_node)

    // 将当前节点添加到已扩展的链表中
    closed_list.add(current_node)

    // 对当前节点的所有邻居节点进行更新操作
    for neighbor in graph.get_neighbors(current_node):
        // 如果邻居节点已经扩展过了,跳过
        if neighbor in closed_list:
            continue
        
        // 计算从起点到