How do I check if a directed graph is acyclic?

后端 未结 11 1770
野的像风
野的像风 2020-11-30 19:16

How do I check if a directed graph is acyclic? And how is the algorithm called? I would appreciate a reference.

11条回答
  •  孤独总比滥情好
    2020-11-30 19:47

    Doing a simple depth-first-search is not good enough to find a cycle. It is possible to visit a node multiple times in a DFS without a cycle existing. Depending on where you start, you also might not visit the entire graph.

    You can check for cycles in a connected component of a graph as follows. Find a node which has only outgoing edges. If there is no such node, then there is a cycle. Start a DFS at that node. When traversing each edge, check whether the edge points back to a node already on your stack. This indicates the existence of a cycle. If you find no such edge, there are no cycles in that connected component.

    As Rutger Prins points out, if your graph is not connected, you need to repeat the search on each connected component.

    As a reference, Tarjan's strongly connected component algorithm is closely related. It will also help you find the cycles, not just report whether they exist.

提交回复
热议问题