Detect a Cycle in a Directed Graph
Problem statement
You are given a directed graph with vertices numbered from 0 through numNodes - 1 and a list of directed edges. Return true if the graph contains at least one directed cycle; otherwise return false.
The graph may be disconnected. A self-loop is a cycle, and parallel edges must be processed independently.
Function
hasDirectedCycle(numNodes: int, edges: int[][]) → booleanExamples
Example 1
numNodes = 4edges = [[0,1],[1,2],[2,0],[2,3]]return = trueThe edges 0 to 1, 1 to 2, and 2 to 0 form a directed cycle.
Example 2
numNodes = 5edges = [[0,1],[1,2],[0,3],[3,4]]return = falseEvery edge follows an acyclic ordering, so all five nodes can be removed topologically.
Constraints
1 <= numNodes <= 2000000 <= edges.length <= 300000edges[i].length == 20 <= edges[i][0], edges[i][1] < numNodesself-loops and parallel directed edges are allowed