AlgoFrames

Cycle reachable from a node

Standard · Write code · about 12 min

Given a directed graph, return true when a cycle can be reached from source. A cycle exists exactly when DFS finds a back edge: an edge to a node that is still on the call stack.

Example 1

Input:

[{"n":5,"edges":[[0,1],[1,2],[2,3],[3,1],[0,4]],"directed":true},0]

Output:

true

Edge 3 to 1 closes the cycle 1, 2, 3.

Example 2

Input:

[{"n":6,"edges":[[0,1],[0,2],[1,3],[2,3],[3,4],[4,5]],"directed":true},0]

Output:

false

Node 3 is reached twice, but never while it is on the stack.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ source < n
  • The graph is directed. Self loops are allowed.

Learn the idea first: Depth-first search, a visual lesson.

More Depth-first search problems