-
Notifications
You must be signed in to change notification settings - Fork 0
/
CheckCycleInDirectedGraphUsingBfs.java
65 lines (51 loc) · 1.71 KB
/
CheckCycleInDirectedGraphUsingBfs.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
60
61
62
63
64
65
package graph;
import java.util.LinkedList;
import java.util.Queue;
public class CheckCycleInDirectedGraphUsingBfs {
private Graph graph;
public CheckCycleInDirectedGraphUsingBfs(Graph graph) {
this.graph = graph;
}
public boolean hasCycle() {
int[] inDegree = new int[graph.getVerticesCount()];
int count = 0;
for (int i = 0; i < graph.getVerticesCount(); i++) {
inDegree[i] = graph.degree(i);
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < graph.getVerticesCount(); i++) {
if (inDegree[i] == 0) {
queue.add(i);
}
}
while (!queue.isEmpty()) {
int node = queue.poll();
count++;
for (int adj : graph.adjacent(node)) {
inDegree[adj]--;
if (inDegree[adj] == 0) {
queue.add(adj);
}
}
}
return count != graph.getVerticesCount();
}
public static void main(String[] args) {
Graph graph = new DirectedGraphAdjacencyList(5);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 1);
graph.addEdge(4, 3);
CheckCycleInDirectedGraphUsingBfs graphCheck = new CheckCycleInDirectedGraphUsingBfs(graph);
System.out.println(graphCheck.hasCycle());
graph = new DirectedGraphAdjacencyList(5);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(4, 1);
graph.addEdge(4, 3);
graphCheck = new CheckCycleInDirectedGraphUsingBfs(graph);
System.out.println(graphCheck.hasCycle());
}
}