[LeetCode] Longest Cycle in a Graph

2360. Longest Cycle in a Graph

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
vector<vector<int>> adj, radj;
vector<int> vis1, vis2, st, rep;
void dfs(int u) {
vis1[u] = true;
for(auto& v : adj[u]) {
if(!vis1[v])
dfs(v);
}
st.push_back(u);
}
void dfs2(int u, int root) {
vis2[u] = true;
rep[u] = root;
for(auto& v : radj[u]) {
if(!vis2[v])
dfs2(v,root);
}
}
public:
int longestCycle(vector<int>& edges) {
int n = edges.size(), res = -1;
adj = radj = vector<vector<int>>(n);
vis1 = vis2 = rep = vector<int>(n);
for(int i = 0; i < n; i++) {
if(edges[i] == -1) continue;
adj[i].push_back(edges[i]);
radj[edges[i]].push_back(i);
}
for(int i = 0; i < n; i++) {
if(!vis1[i]) dfs(i);
}
while(!st.empty()) {
auto u = st.back(); st.pop_back();
if(vis2[u]) continue;
dfs2(u,u);
}
unordered_map<int, int> freq;
for(int i = 0; i < n; i++) {
freq[rep[i]]++;
}
for(auto& [_, c] : freq) {
if(c == 1) continue;
res = max(res, c);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/31/PS/LeetCode/longest-cycle-in-a-graph/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.