-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab7q7.java
More file actions
58 lines (47 loc) · 1.55 KB
/
Lab7q7.java
File metadata and controls
58 lines (47 loc) · 1.55 KB
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
import java.util.*;
public class Lab7q7 {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
int vertices = 4;
for (int i = 0; i < vertices; i++) {
graph.add(new ArrayList<>());
}
graph.get(0).add(1);
graph.get(0).add(2);
graph.get(1).add(3);
// graph.get(2).add(1);
graph.get(3).add(2);
boolean hasCycle = isCyclicBFS(graph, vertices);
if (hasCycle) {
System.out.println("The graph contains a cycle.");
} else {
System.out.println("The graph does not contain a cycle.");
}
}
static boolean isCyclicBFS(ArrayList<ArrayList<Integer>> graph, int vertices) {
int[] inDegree = new int[vertices];
for (int i = 0; i < vertices; i++) {
for (int neighbor : graph.get(i)) {
inDegree[neighbor]++;
}
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < vertices; i++) {
if (inDegree[i] == 0) {
queue.add(i);
}
}
int count = 0;
while (!queue.isEmpty()) {
int current = queue.poll();
count++;
for (int neighbor : graph.get(current)) {
inDegree[neighbor]--;
if (inDegree[neighbor] == 0) {
queue.add(neighbor);
}
}
}
return count != vertices;
}
}