A*算法不是按照增量成本顺序从边缘中弹出节点,而是按照f(n) = g(n) + h(n)的值从边缘中弹出节点,其中g(n)是从起始节点到n节点的实际成本,h(n)是从n节点到目标节点的估计成本。
A*算法的伪代码如下:
function AStarSearch(start, goal):
openSet := {start} // 待探索的节点集合
closedSet := {} // 已探索的节点集合
gScore := {} // 从起始节点到各节点的实际成本
hScore := {} // 从各节点到目标节点的估计成本
fScore := {} // f(n) = g(n) + h(n)
gScore[start] := 0
hScore[start] := heuristic(start, goal)
fScore[start] := hScore[start]
while openSet is not empty:
current := node in openSet with lowest fScore[current] // 选择f(n)值最小的节点
if current = goal:
return reconstructPath(cameFrom, current)
openSet.remove(current)
closedSet.add(current)
for neighbor in current.neighbors:
if neighbor in closedSet:
continue // 忽略已探索的节点
tentativeGScore := gScore[current] + distance(current, neighbor) // 计算从起始节点经过当前节点到邻居节点的成本
if neighbor not in openSet:
openSet.add(neighbor)
else if tentativeGScore >= gScore[neighbor]:
continue // 不是更好的路径
// 更新邻居节点的成本和父节点
cameFrom[neighbor] := current
gScore[neighbor] := tentativeGScore
hScore[neighbor] := heuristic(neighbor, goal)
fScore[neighbor] := gScore[neighbor] + hScore[neighbor]
return null // 未找到路径
在A*算法中,通过选择f(n)值最小的节点来扩展搜索。这样可以确保优先考虑那些离目标节点最近的节点,但不一定按照增量成本顺序弹出节点。