A星尋路演算法的Lua實現__lua

來源:互聯網
上載者:User

A*搜尋演算法俗稱A星演算法。這是一種在圖形平面上,有多個節點的路徑,求出最低通過成本的演算法。

這裡有一篇前輩的文章,很適合新手學習 莫水千流:A星尋路演算法介紹 http://www.cnblogs.com/zhoug2020/p/3468167.html 。

對A星演算法的理解還是要從公式 F = G + H開始:在節點化的地圖上,每一步的操作,使得已走距離 + 距離終點距離最小。具體的實現上是維護一個open表和一個closed表。(看到一篇用遞迴實現的文章,也是很贊。)

花了一點時間,也參考了一些別人的實現,用Lua實現了自己的A*。
完整的Lua代碼請到我的GitHub上下載。https://github.com/MagicDavid20/LuaProj/blob/master/DOD/src/app/arithmetic/AStarFindRoute.lua 這是關鍵實現:

while (table.nums(OPEN_LIST) > 0) do    CURRENT_POS = OPEN_LIST[1]    table.remove(OPEN_LIST, 1)    OPEN_MAP[CURRENT_POS.key] = nil    if IS_SAME_P(CURRENT_POS, END_POS) then        return makePath(CURRENT_POS)    else        CLOSED_MAP[CURRENT_POS.key] = CURRENT_POS        local nextPoints = getNextPoints(CURRENT_POS)        for i = 1, #nextPoints do            local nextPoint = nextPoints[i]            if (OPEN_MAP[nextPoint.key] == nil )and (CLOSED_MAP[nextPoint.key] == nil) and (IS_BARRIER(nextPoint, BARRIER_LIST) == false) then                OPEN_MAP[nextPoint.key] = nextPoint                table.insert(OPEN_LIST, nextPoint)            end        end        table.sort(OPEN_LIST, COMPARE_FUNC)    endendreturn nil
這裡是測試案例


(圖片來自莫水千流:A星尋路演算法介紹 http://www.cnblogs.com/zhoug2020/p/3468167.html ,資料是類比的這張圖片。)

    local prop = {}    prop.x = 7    prop.y = 6    prop.startPos = { x = 2, y = 3 }    prop.endPos = { x = 6, y = 2 }    prop.barrageList = {}    prop.barrageList[1] = { x = 4, y = 2 }    prop.barrageList[2] = { x = 4, y = 3 }    prop.barrageList[3] = { x = 4, y = 4 }    prop.barrageList[4] = { x = 4, y = 5 }    prop.barrageList[5] = { x = 2, y = 2 }    local path = AStarFindRoute.init(prop)    local src = ""    for i, point in ipairs(path) do        src = src..point.key.."->"    end    print("david say path is "..src)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.