-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 178.java
More file actions
38 lines (29 loc) · 948 Bytes
/
Day 178.java
File metadata and controls
38 lines (29 loc) · 948 Bytes
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
import java.util.*;
class Solution {
public int longestCycle(int V, int[][] edges) {
int[] out = new int[V];
for (int i = 0; i < V; i++) out[i] = -1;
for (int[] e : edges) {
out[e[0]] = e[1];
}
boolean[] visited = new boolean[V];
int ans = -1;
for (int i = 0; i < V; i++) {
if (visited[i]) continue;
int curr = i;
int step = 0;
HashMap<Integer, Integer> map = new HashMap<>();
while (curr != -1 && !visited[curr]) {
visited[curr] = true;
map.put(curr, step++);
curr = out[curr];
if (curr != -1 && map.containsKey(curr)) {
int cycleLen = step - map.get(curr);
ans = Math.max(ans, cycleLen);
break;
}
}
}
return ans;
}
}