Problem · Graph
Detect a Cycle in a Directed Graph
Learn this problemProblem statement
Given n vertices numbered from 0 to n - 1 and a list of directed edges, return whether the graph contains at least one directed cycle.
Function
hasDirectedCycle(n: int, edges: int[][]) → booleanExamples
Example 1
n = 4edges = [[0,1],[1,2],[2,0],[2,3]]return = trueThe path 0 -> 1 -> 2 -> 0 is a directed cycle.
Example 2
n = 4edges = [[0,1],[0,2],[1,3],[2,3]]return = falseNo directed path returns to an active ancestor.
Constraints
1 <= n <= 1000000 <= edges.length <= 200000- Every edge contains two valid vertex indices.
- Parallel edges may appear.