#2360

Longest Cycle in a Graph

candidate master · 1405 · lc hard +32 · verified · 50.5% accepted · 2,542 likes · top 38%

Description

A directed graph of n nodes (labeled 0 to n - 1) is given where every node has at most one outgoing edge. It is encoded as a 0-indexed array edges of length n; edges[i] is the node that i points to, or -1 if i has no outgoing edge.

Return the length of the longest cycle present in the graph, or -1 if no cycle exists.

A cycle is a closed path that returns to its starting node.

Example 1:

Input: edges = [3,3,4,2,3]
Output: 3
Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.
The length of this cycle is 3, so 3 is returned.

Example 2:

Input: edges = [2,-1,3,1]
Output: -1
Explanation: There are no cycles in this graph.

Code

1
2
3