Graphs Cycle detection
454. Cycle in a Directed Graph
You are given a directed graph with n vertices, numbered from 0 to n - 1. Each pair [u, v] in edges
is an edge from vertex u to vertex v. An edge can be followed only in its own direction, from u to v.
A cycle is a path that follows one or more edges and ends at the vertex where it started. An edge from a
vertex to itself, [u, u], is a cycle of one edge.
Return true if the graph has at least one cycle, and false if it has none.
Example 1
Input: n = 6
edges = [[0, 1],
[1, 2],
[2, 3],
[3, 1],
[4, 3],
[4, 5]]
trueExplanation: The path 1 → 2 → 3 → 1 ends where it started. Vertices 0, 4 and 5 are on no cycle, but one cycle is enough.
Example 2
Input: n = 4, edges = [[0, 1], [0, 2], [1, 3], [2, 3]]
falseExplanation: Vertex 3 can be reached from 0 in two ways, through 1 and through 2. But no edge leaves vertex 3, and no path ever comes back to the vertex where it started.
Example 3
Input: n = 3, edges = [[0, 1], [2, 2]]
trueExplanation: The edge [2,2] goes from vertex 2 back to itself, which is a cycle of one edge.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1050 ≤ edges.length ≤ 2 × 105edges[i].length == 20 ≤ ui, vi < n- No edge appears twice.
[u, v]and[v, u]are different edges.
Clarifying questions
What you would ask an interviewer before writing any code.