local queue = {} --数组模拟队列 local qPtr = 1--qPtr代表队列头 queue[qPtr] = "v1"--从v1开始遍历,队首放入首个结点 local visited = { queue[qPtr] } --存储访问过的结点
repeat local node = queue[qPtr] local neighborList = map[node] --node的邻接表 for i = 1, #neighborList do ifnot contains(visited, neighborList[i]) then queue[#queue + 1] = neighborList[i] table.insert(visited, neighborList[i]) end end queue[qPtr] = "" qPtr = qPtr + 1 until(qPtr > #queue)
--结果输出 localoutput = "" for i = 1, #visited do output = output .. visited[i] .. "," end print(string.sub(output, 1, #output - 1))
local stack = {} --数组模拟栈 stack[1] = "v1"--从v1开始遍历,栈底放入首个结点 local visited = { stack[1] } --存储访问过的结点 local found = false--用于标记当前结点的邻接结点是否已经都遍历过了
repeat local node = stack[#stack] --peek操作 local neighborList = map[node] --node的邻接表 found = false for i = 1, #neighborList do if found then break end ifnot contains(visited, neighborList[i]) then stack[#stack + 1] = neighborList[i] --push操作 table.insert(visited, neighborList[i]) found = true end end ifnot found then stack[#stack] = nil--pop操作 end until(#stack == 0)
--结果输出 localoutput = "" for i = 1, #visited do output = output .. visited[i] .. "," end print(string.sub(output, 1, #output - 1))