1.实现思路:首先使用lua唯一的数据结构table实现图,随后对图中每个节点进行初始化(算出每个节点的入度),把入度为0的节点放入到queue队列中。之后设置一个临时变量current等于每次queue pop出的结果,并把这个结果存储在result表中,每次pop一次都要进行一次遍历(因为可能会出现新的入度为0的节点)并把这些新出现的节点加入到queue中去,直到queue的大小为0(有点类似于二叉树的层序遍历)。
2.代码实现:
local graph = {
[1] = {2},
[2] = {4},
[3] = {4,5},
[4] = {5},
[5] = {6,7},
[6] = {7},
[7] = {},
}
local function topologicalSort(graph)
local indegree = {}--store degree
local result = {}--store the finnal result
--first initialize the indegree
for node,neighbors in pairs(graph) do
indegree[node] = indegree[node] or 0
for _,neighbor in ipairs(neighbors) do
indegree[neighbor] = (indegree[neighbor] or 0) + 1
-- 这里是怕出现nil的情况
end
end
local queue = {}
for node,degree in pairs(indegree) do
if degree == 0 then
table.insert(queue,node)
end
end
while #queue >0 do
local current = table.remove(queue,1)
table.insert(result,current)
--reinitialize the indegree
for _,neighbor in ipairs(graph[current] or {}) do
indegree[neighbor] = indegree[neighbor] -1
if indegree[neighbor] ==0 then
table.insert(queue,neighbor)
end
end
end
if #result == table.maxn(graph) then
return result
else
return nil
end
end
local result = topologicalSort(graph)
if result then
print("the answer :",table.concat(result,"->"))
else
print("the circle exsit")
end