- Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathPR2.java
59 lines (43 loc) · 1.55 KB
/
PR2.java
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
49
50
51
52
53
54
55
56
57
58
59
importjava.util.*;
publicclassPR2 {
publicstaticbooleandetectCycle(int[][] edgeList) {
if (edgeList.length == 0) {
returnfalse;
}
Map<Integer, Set<Integer>> graph = newHashMap<>();
int[] inorder = newint[edgeList.length];
for (int[] edge : edgeList) {
graph.putIfAbsent(edge[0], newHashSet<>());
graph.get(edge[0]).add(edge[1]);
inorder[edge[1]]++;
}
Queue<Integer> q = newLinkedList<>();
for (inti = 0; i < inorder.length; i++) {
if (inorder[i] == 0) {
q.offer(i);
}
}
intnodeCount = 0;
while (!q.isEmpty()) {
intkey = q.poll();
++nodeCount;
if (!graph.containsKey(key)) {
continue;
}
for (intneighbour : graph.get(key)) {
inorder[neighbour]--;
if (inorder[neighbour] == 0) {
q.offer(neighbour);
}
}
}
returnedgeList.length - nodeCount > 1;
}
publicstaticvoidmain(String[] args) {
int[][] edgeList1 = newint[][] { { 0, 1 }, { 1, 3 }, { 2, 3 }, { 1, 2 }, { 4, 1 }, { 0, 4 }, { 1, 3 } };
int[][] edgeList2 = newint[][] { { 0, 1 }, { 1, 3 }, { 2, 3 }, { 3, 4 }, { 1, 2 }, { 4, 1 }, { 0, 4 } };
System.out.println(detectCycle(edgeList1)); // no cycle - return false
System.out.println(detectCycle(edgeList2)); // cycle present - return true
return;
}
}