欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

寻找图的路径之寻路算法

程序员文章站 2022-05-21 17:52:17
...
--到地图去的关系表
local tbToMap = {}
tbToMap[1000] = {1001,1003,1010}
tbToMap[1001] = {1000,1002,1004,1009}
tbToMap[1002] = {1005,1001,1009}
tbToMap[1003] = {1000,1006,1004}
tbToMap[1004] = {1007,1001,1003,1005}
tbToMap[1005] = {1002,1004,1011}
tbToMap[1006] = {1003,1007}
tbToMap[1007] = {1004,1006,1008}
tbToMap[1008] = {1007}
tbToMap[1009] = {1001,1002,1010}
tbToMap[1010] = {1009,1000}
tbToMap[1011] = {1005}

local tbResult = {}--所有遍历结果

local FIRID = 1008
local LASID = 1002
local tbGoBy = {}--走过的路
local tbBlindAlley = {}--死路节点

local num = 0
local maxRecursionNum = 100--最大递归上限

local g_findOver = false

local function findMapPath(_firstId,_lastId)
    num = num + 1
    if num > maxRecursionNum then--递归超过上限
        return
    end

    print(_firstId, "_firstId = ")
    tbGoBy[_firstId] = true
    table.insert(tbResult, _firstId)
    if _firstId == _lastId then
        return
    else
        local dt = tbToMap[_firstId]
        for k, v in ipairs(dt) do
            if not tbGoBy[v] then
                local value = findMapPath(v, _lastId)
                print(value, "value = ")
                if value == nil then
                    return
                end
            end
        end

        --if not g_findOver then
            tbBlindAlley[_firstId] = true
        --end
        return _firstId
    end
end
--findMapPath(1008,1010)
findMapPath(1006,1009)
--findMapPath(1006,1002)

dump(tbBlindAlley, "tbBlindAlley = ")
print(num, "num = ")

dump(tbResult, "tbResult = ")

for i = #tbResult, 1, -1 do
    local mapId = tbResult[i]
    if tbBlindAlley[mapId] then
        table.remove(tbResult, i)
    end
end

dump(tbResult, "tbResult = ")