Graphs · Exercise 50 of 100

Directed cycles with DFS

During a directed depth-first search, a vertex is active from the moment you enter it until you finish exploring its outgoing edges. An edge to an active vertex closes a cycle because the current search path already leads from that vertex to you. An edge to a finished vertex alone does not establish a cycle.

Try it yourself

Run recursive DFS from A, exploring outgoing neighbors alphabetically. The arrows are A to B, A to C, B to D, C to D, C to E and E to C. Which vertex is the destination of the first edge found to an active vertex?

One-step hint

Keep the current chain of recursive calls on paper, erasing a vertex when its call finishes. Test each arrow's destination against that chain.

Worked solution
  1. DFS follows A to B to D, then finishes D and B before entering C. The arrow from C to D reaches a finished vertex.
  2. C next enters E. The arrow from E leads back to C while C is still active, so the destination is C.
DSA compiler