Detect Cycle in a Directed Graph
MediumP2Coding
A directed graph has n vertices labelled 0..n - 1. Each entry [u, v] of edges is an edge from u to v. Return true if the graph contains a directed cycle. A self-loop [u, u] counts as a cycle.
Example 1
- Input
- n = 4, edges = [[0,1],[1,2],[2,3],[3,1]]
- Output
- true
- Why
- 1 -> 2 -> 3 -> 1 is a cycle.
Example 2
- Input
- n = 4, edges = [[0,1],[1,2],[2,3]]
- Output
- false
Constraints
- 1 <= n <= 10^4
- 0 <= edges.length <= 5 * 10^4
- 0 <= u, v < n
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 10. ⌘Enter runs, ⌘⇧Enter submits.