2360. Longest Cycle in a Graph Hard

@problem@discussion
#Depth-First Search#Graph#Topological Sort



1/**
2 * [2360] Longest Cycle in a Graph
3 *
4 * You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.
5 * The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.
6 * Return the length of the longest cycle in the graph. If no cycle exists, return -1.
7 * A cycle is a path that starts and ends at the same node.
8 *  
9 * Example 1:
10 * <img alt="" src="https://assets.leetcode.com/uploads/2022/06/08/graph4drawio-5.png" style="width: 335px; height: 191px;" />
11 * Input: edges = [3,3,4,2,3]
12 * Output: 3
13 * Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.
14 * The length of this cycle is 3, so 3 is returned.
15 * 
16 * Example 2:
17 * <img alt="" src="https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-1.png" style="width: 171px; height: 161px;" />
18 * Input: edges = [2,-1,3,1]
19 * Output: -1
20 * Explanation: There are no cycles in this graph.
21 * 
22 *  
23 * Constraints:
24 * 
25 * 	n == edges.length
26 * 	2 <= n <= 10^5
27 * 	-1 <= edges[i] < n
28 * 	edges[i] != i
29 * 
30 */
31pub struct Solution {}
32
33// problem: https://leetcode.com/problems/longest-cycle-in-a-graph/
34// discuss: https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/?currentPage=1&orderBy=most_votes&query=
35
36// submission codes start here
37
38impl Solution {
39    pub fn longest_cycle(edges: Vec<i32>) -> i32 {
40        0
41    }
42}
43
44// submission codes end
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn test_2360() {
52    }
53}
54


Back
© 2025 bowen.ge All Rights Reserved.