digraph_utils:is_acyclic/1
返回false后,如何(有效地)在Erlang有向图中找到循环或循环?
编辑:is_acyclic
为defined as loop_vertices(G) =:= [] andalso topsort(G) =/= false.
答案 0 :(得分:4)
您可以使用digraph_utils:cyclic_strong_components/1
。
cyclic_strong_components(Digraph) -> [StrongComponent].
返回strongly connected components的列表。每个强烈 组件由其顶点表示。顶点的顺序 并且组件的顺序是任意的。只有顶点 包含在Digraph中的某些循环中,否则返回 list等于
strong_components/1
返回的列表。
测试:
get_cycles() ->
G = digraph:new(),
Vertices = [a, c, b, d, e, f, g],
lists:foreach(fun(V) -> digraph:add_vertex(G, V) end, Vertices),
Edges = [{a,b},{b,c},{c,a},{b,d},{d,e},{e,b},{a,f},{f,g},{g,f}],
lists:foreach(fun({V1,V2}) -> digraph:add_edge(G, V1, V2) end, Edges),
digraph_utils:cyclic_strong_components(G).
输出:
3> test:get_cycles().
[[c,a,b,d,e],[f,g]]
注意:强>
由于每个组件中顶点的顺序是任意的,如果要查找确切的路径,可以使用digraph:get_cycle/2
。例如,在上述情况下,digraph:get_cycle(G, c)
将为您提供[c,d,a,b,c]
。
编辑 - 另一个重要说明:
虽然每个周期都是循环强连接组件,但情况恰恰相反。这意味着您在一个这样的组件中可能只有几个循环
所以在这种情况下,如果你想要获得每个周期,你可以把每一个组件扔掉并分成它的简单周期。
所以'扩展'上面的版本将是:
get_cycles() ->
G = digraph:new(),
Vertices = [a, c, b, d, e, f, g],
lists:foreach(fun(V) -> digraph:add_vertex(G, V) end, Vertices),
Edges = [{a,b},{b,c},{c,a},{b,d},{d,e},{e,b},{a,f},{f,g},{g,f}],
lists:foreach(fun({V1,V2}) -> digraph:add_edge(G, V1, V2) end, Edges),
Components = digraph_utils:cyclic_strong_components(G),
lists:foldl(fun(Comp, Acc) -> get_more_cycles(G,Comp,[]) ++ Acc end, [], Components).
get_more_cycles(_G, [], Acc) ->
Acc;
get_more_cycles(G, [H|T], Acc) ->
Cycle = digraph:get_cycle(G,H),
get_more_cycles(G, T -- Cycle, [Cycle|Acc]).
输出:
3> test:get_cycles().
[[f,g,f],[d,e,b,d],[c,a,b,c]]