Validate a Directed Graph
Problem statement
Return whether a graph is valid under the rule below.
For this exercise, assume validity means the directed graph contains no directed cycle. Vertices are numbered from 0 to n - 1, and each pair [u, v] in edges is an edge from u to v.
The graph may be disconnected. A self-loop is a cycle. Repeated copies of an edge are allowed and do not by themselves form a cycle. The empty graph is acyclic. Return true for an acyclic graph and false otherwise.
Function
isDirectedAcyclic(n: int, edges: int[][]) → booleanExamples
Example 1
n = 4edges = [[0,1],[0,2],[2,3]]return = trueEvery edge follows the order 0, 1, 2, 3: each source appears before its destination. No directed path can return to its starting vertex, so the graph is acyclic.
Example 2
n = 3edges = [[0,1],[1,2],[2,0]]return = falseThe edges form the directed cycle 0 → 1 → 2 → 0, so the graph is invalid.
Constraints
0 <= n <= 20000 <= edges.length <= 10000edges[i].length == 2- Every edge endpoint is an integer in
[0, n). Ifn == 0,edgesis empty.