我如何检查有向图是否为无环图?该算法名称是什么?如果有参考资料将不胜感激。
我如何检查有向图是否为无环图?该算法名称是什么?如果有参考资料将不胜感激。
这是我的 Ruby 实现 剥离叶节点算法。
def detect_cycles(initial_graph, number_of_iterations=-1)
# If we keep peeling off leaf nodes, one of two things will happen
# A) We will eventually peel off all nodes: The graph is acyclic.
# B) We will get to a point where there is no leaf, yet the graph is not empty: The graph is cyclic.
graph = initial_graph
iteration = 0
loop do
iteration += 1
if number_of_iterations > 0 && iteration > number_of_iterations
raise "prevented infinite loop"
end
if graph.nodes.empty?
#puts "the graph is without cycles"
return false
end
leaf_nodes = graph.nodes.select { |node| node.leaving_edges.empty? }
if leaf_nodes.empty?
#puts "the graph contain cycles"
return true
end
nodes2 = graph.nodes.reject { |node| leaf_nodes.member?(node) }
edges2 = graph.edges.reject { |edge| leaf_nodes.member?(edge.destination) }
graph = Graph.new(nodes2, edges2)
end
raise "should not happen"
end
你可以使用我在这里的答案中提到的寻找循环的反转方法https://dev59.com/G7joa4cB1Zd3GeqPDr_a#60196714
def is_acyclic(graph):
return not has_cycle(graph)