Algorithm for finding shortest cycles in directed graph

旧城冷巷雨未停 提交于 2019-12-08 11:37:49

问题


A shortest cycle is one with the minimum number of edges.

For example, given a graph:

The shortest cycles are: ACDA, DABD

If I only needed to find one shortest cycle, I would just run BFS on every vertex and keep track of the smallest cycle. But I don't know how to enumerate all smallest cycles.

There is a similar SO question on enumerating minimal cycles in a digraph, but there a minimal cycle is one which is not a union of smaller cycles. Here I am only looking for the cycles with the minimum number of edges.


回答1:


Run a number of DFS searches as in topological sort: start from a random vertex, and continue running new DFS searches as long as there are some unexplored vertices.

In a search, as soon as you find a back edge, you know that (1) there's a cycle (2) the number of edges in that cycle. If you also need to get a list of edges in the cycle, keep an array for each "currently detected cycle" and fill it as you backtrack in the DFS call graph. If the back-edge was a node A->B, When you'll reach back node B, the array is going to contain all edges in the cycle.

Of course, keep in track the "shortest cycle found so far" to avoid bookkeeping edge lists for cycles that are longer than this minimum.



来源:https://stackoverflow.com/questions/34703557/algorithm-for-finding-shortest-cycles-in-directed-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!