-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
40 lines (31 loc) · 1001 Bytes
/
Copy pathsolution.java
File metadata and controls
40 lines (31 loc) · 1001 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
39
40
import java.util.*;
class Solution {
public int longestCycle(int V, int[][] edges) {
int[] adj = new int[V];
Arrays.fill(adj, -1);
for (int[] e : edges) {
adj[e[0]] = e[1];
}
boolean[] visited = new boolean[V];
int maxCycle = -1;
for (int i = 0; i < V; i++) {
if (visited[i])
continue;
HashMap<Integer, Integer> map = new HashMap<>();
int node = i, step = 0;
while (node != -1) {
if (map.containsKey(node)) {
int cycleLen = step - map.get(node);
maxCycle = Math.max(maxCycle, cycleLen);
break;
}
if (visited[node])
break;
map.put(node, step++);
visited[node] = true;
node = adj[node];
}
}
return maxCycle;
}
}