You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.
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.
Return the length of the longest cycle in the graph. If no cycle exists, return -1.
A cycle is a path that starts and ends at the same 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.
Constraints:
- n == edges.length
- 2 <= n <= 105
- -1 <= edges[i] < n
- edges[i] != i
每一个 node 可能有多个 from, 但是 to 只有一个, 所以我们将每个 node 的 to 收集起来作为当前 node 的 parents, 同时记录下 node[i]与 parents[i]的距离, 我们 bfs 更新 parents, 假设 parents[i] = (parent, parent_distance), parents[parent] = (parent_of_parent, parent_of_parent_distance), 那我们就可以更新 parents[i] = (parent_of_parent, parent_distance + parent_of_parent_distance), 但是要注意, 如果 parent == parent_of_parent 则证明 parents[parent]已经形成环路了, 我们就没必要再更新当前 parents[i]了, 因为此时 parent_distance + parent_of_parent_distance 是当前节点到环路的入口节点之间的距离加上环路的长度, 对我们的答案没有任何用处。如果 parent_of_parent == i, 则证明当前节点形成环路了, 此时的 parent_distance + parent_of_parent_distance 就是环路的长度, 我们只需要收集该值的最大值就是最终答案了
impl Solution {
pub fn longest_cycle(edges: Vec<i32>) -> i32 {
let mut parents: Vec<(i32, i32)> = edges.into_iter().map(|v| (v, 1)).collect();
let mut ans = 0;
loop {
let mut changed = false;
for i in 0..parents.len() {
if parents[i].0 < 0 {
continue;
}
let (p, pn) = parents[i];
let (pp, ppn) = parents[p as usize];
if p == pp {
continue;
}
parents[i] = (pp, pn + ppn);
changed = true;
if pp == i as i32 {
ans = ans.max(pn + ppn);
}
}
if !changed {
break;
}
}
if ans == 0 {
-1
} else {
ans
}
}
}

给定一个有向图,每个节点最多有一个出边。返回图中最长循环的长度,若无循环则返回-1。通过 BFS 更新节点的父节点及距离,当发现环路时,计算环路长度并更新答案。
796

被折叠的 条评论
为什么被折叠?



