[Math] Tarjan’s algorithm to determine wheter a directed graph has a cycle

algorithmscomputer sciencegraph theory

I want to know if a directed graph has a cycle; something like

1->2->3->2 ...
1->2->3->4->3...
1->1->1->1...

So, I'm considering the Tarjan's strongly connected algorithm.

Do you think that with this algorithm I'll be able to know if some directed graph has a cycle?

Thanks!

Best Answer

Tarjan's algorithm may be used to detect cycles in a directed graph as follows: When the root node of a (maximal) strongly connected component (SCC) is detected, the nodes in the SCC are popped from the stack. At that point, if more than one node is popped, then it is known that the graph contains a cycle. If the SCC contains a single node, one has to check whether that node has a "self-loop" (which gives a cycle) or not (that is, the node makes up a trivial SCC).

Said otherwise, if the directed graph has no cycles, Tarjan's algorithm will only find SCCs consisting of individual nodes without self-loops.


If the cycle needs to be identified and the SCC found has more than one node, one can perform a depth-first search from the SCC root, limited to the nodes that are in that SCC and until the root of the SCC is re-entered.

In fact, in practice, cycle detection in directed graphs is performed by two nested depth-first searches, without concern for the enumeration of SCCs, especially when cycles have to go through some designated nodes.

When the "outer" DFS is about to retreat from a (designated) node $v$, a second DFS is run from $v$ to see if some node $u$ currently on the stack of the outer DFS may be reached from $v$.

If that is the case, we have a cycle reachable from the node from which the first DFS started. Such a cycle goes through both $v$, the node from which the outer DFS is about to retreat, and $u$, the node on the stack of the outer DFS found during the inner DFS. We know we can reach $v$ from $u$ because $u$ is on the stack of the outer DFS. We know we can reach $u$ from $v$ because the inner DFS says so.


The nested DFS algorithm is not asymptotically faster than Tarjan's algorithm, but often performs better.

Related Question