A*搜尋演算法
(重新導向自A*)
頁面Module:Message box/mbox.css沒有內容。
此條目需要補充更多來源。 (2015年6月30日) |
頁面Module:Message box/mbox.css沒有內容。
此條目需要擴充。 (2018年3月5日) |
A*搜尋演算法(Template:Langx)是一種在圖形平面上,有多個節點的路徑,求出最低通過成本的演算法。常用於遊戲中的NPC的移動計算,或網絡遊戲的BOT的移動計算上。
該演算法綜合了最良優先搜尋和戴克斯特拉演算法的優點:在進行啟發式搜尋提高演算法效率的同時,可以保證找到一條最佳路徑(需要評估函數滿足單調性)。
在此演算法中,如果以<math>g(n)</math>表示從起點到任意頂點<math>n</math>的實際距離,<math>h(n)</math>表示任意頂點<math>n</math>到目標頂點的估算距離(根據所採用的評估函數的不同而變化),那麼A*演算法的估算函數為:
- <math>f(n) = g(n) + h(n)</math>
這個公式遵循以下特性:
- 如果<math>g(n)</math>為0,即只計算任意頂點<math>n</math>到目標的評估函數<math>h(n)</math>,而不計算起點到頂點<math>n</math>的距離,則演算法轉化為使用貪心策略的最良優先搜尋,速度最快,但可能得不出最佳解;
- 如果<math>h(n)</math>不大於頂點<math>n</math>到目標頂點的實際距離,則一定可以求出最佳解,而且<math>h(n)</math>越小,需要計算的節點越多,演算法效率越低,常見的評估函數有——歐幾里得距離、曼哈頓距離、切比雪夫距離;
- 如果<math>h(n)</math>為0,即只需求出起點到任意頂點<math>n</math>的最短路徑<math>g(n)</math>,而不計算任何評估函數<math>h(n)</math>,則轉化為最短路問題,即戴克斯特拉演算法,此時需要計算最多的頂點;
偽代碼[編輯]
//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
相關連結[編輯]
外部連結[編輯]
package.lua第80行Lua錯誤:module 'Module:Navbar/configuration' not found