A*搜尋演算法

本页使用了标题或全文手工转换,现处于澳门繁体模式
求聞百科,共筆求聞
A*搜尋演算法的演示圖

A*搜尋演算法(A* search algorithm)是一種在圖形平面上,有多個節點路徑,求出最低通過成本演算法。常用於遊戲中的NPC的移動計算,或網絡遊戲的BOT的移動計算上。

該演算法綜合了最良優先搜尋Dijkstra演算法的優點:在進行啟發式搜尋提高演算法效率的同時,可以保證找到一條最佳路徑(基於評估函數)。

在此演算法中,如果以表示從起點到任意頂點的實際距離,表示任意頂點到目標頂點的估算距離(根據所採用的評估函數的不同而變化),那麼A*演算法的估算函數為:

這個公式遵循以下特性:

  • 如果為0,即只計算任意頂點到目標的評估函數,而不計算起點到頂點的距離,則演算法轉化為使用貪心策略的最良優先搜尋,速度最快,但可能得不出最佳解;
  • 如果不大於頂點到目標頂點的實際距離,則一定可以求出最佳解,而且越小,需要計算的節點越多,演算法效率越低,常見的評估函數有——歐幾里得距離曼哈頓距離切比雪夫距離
  • 如果為0,即只需求出起點到任意頂點的最短路徑,而不計算任何評估函數,則轉化為最短路問題問題,即Dijkstra演算法,此時需要計算最多的頂點;

虛擬碼

//Matlab语言
 function A*(start,goal)
     closedset := the empty set                 //已经被估算的节点集合
     openset := set containing the initial node //将要被估算的节点集合,初始只包含start
     came_from := empty map
     g_score[start] := 0                        //g(n)
     h_score[start] := heuristic_estimate_of_distance(start, goal)    //通过估计函数 估计h(start)
     f_score[start] := h_score[start]            //f(n)=h(n)+g(n),由于g(n)=0,所以省略
     while openset is not empty                 //当将被估算的节点存在时,执行循环
         x := the node in openset having the lowest f_score[] value   //在将被估计的集合中找到f(x)最小的节点
         if x = goal            //x为终点,执行
             return reconstruct_path(came_from,goal)   //返回到x的最佳路徑
         remove x from openset      //x节点从将被估算的节点中刪除
         add x to closedset      //x节点插入已经被估算的节点
         for each y in neighbor_nodes(x)  //循环遍历与x相鄰节点
             if y in closedset           //y已被估值,跳过
                 continue
             tentative_g_score := g_score[x] + dist_between(x,y)    //从起点到节点y的距离

             if y not in openset          //y不是将被估算的节点
                 tentative_is_better := true     //暫时判断为更好
             elseif tentative_g_score < g_score[y]         //如果起点到y的距离小于y的实际距离
                 tentative_is_better := true         //暫时判断为更好
             else
                 tentative_is_better := false           //否则判断为更差
             if tentative_is_better = true            //如果判断为更好
                 came_from[y] := x                  //y设为x的子节点
                 g_score[y] := tentative_g_score    //更新y到原点的距离
                 h_score[y] := heuristic_estimate_of_distance(y, goal) //估计y到终点的距离
                 f_score[y] := g_score[y] + h_score[y]
                 add y to openset         //y插入将被估算的节点中
     return failure
 
 function reconstruct_path(came_from,current_node)
     if came_from[current_node] is set
         p = reconstruct_path(came_from,came_from[current_node])
         return (p + current_node)
     else
         return current_node

相關連結

外部連結

A* 演算法簡介 (A* Algorithm Brief)