-
Notifications
You must be signed in to change notification settings - Fork 0
/
cycle_detection_in _directed_graph.java
73 lines (61 loc) · 2.33 KB
/
cycle_detection_in _directed_graph.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
66
67
68
69
70
71
72
73
import utils.*;
import java.util.*;
class main{
//using BFS we can detect cycle in directed graph. Idea is to use degree of vertex.
//if we have |V| vertices and we pop N no. of verticec from queue.
//if|V|==N then there is no cycle. else there is a cycle.
static boolean hasCycle(ArrayList<Edge> graph[]){
int noOfNode = graph.length;
int degree[] = new int[noOfNode];
LinkedList<Integer> topologicalPrint = new LinkedList<>();
boolean cycle = true;
for(int i=0;i<noOfNode;i++){
for(Edge e : graph[i]){
degree[e.vertex]++;
}
}
int noOfPopedVerticex=0;
//BFS Approach.
Queue<Integer> queue = new LinkedList<>();
for(int i=0;i<noOfNode;i++){
if(degree[i]==0) queue.add(i);
}
while(queue.size()>0){
int currentVertex = queue.remove();
topologicalPrint.addLast(currentVertex);
for(Edge e : graph[currentVertex]){
int val = --degree[e.vertex];
if(val==0) queue.add(e.vertex);
}
noOfPopedVerticex++;
}
return noOfNode==noOfPopedVerticex?false:true;
}
// Algorighm-
// 1.[VARIABLE INITIALIZATION] degree[|V|]={0},noOfNode=|V|,count_of_poped_vertices=0,
// 2.calculate degree of all vertices (in degree).
// 3.push all vertex which is having 0 degree to Q (QUEUE).
// 4.while Q!=null
// 4.1. pop vertex from queue currentVertex <-Q.pop().
// 4.2. for all neighbour vertex of currentVertex.
// 4.2.1. decrement neighbour vertex degree by 1.
// 4.2.2. if new degree becomes 0 push into the Q.
// 4.3. count_of_poped_vertices++.
// 5. if noOfNode==noOfPopedVerticex return false else true.
public static void main(String args[]){
Graph g = new Graph(8);
ArrayList<Edge> graph[] = g.graph;
g.addEdge(0,1,0,false);
g.addEdge(1,2,0,false);
g.addEdge(1,3,0,false);
g.addEdge(2,4,0,false);
g.addEdge(2,5,0,false);
g.addEdge(3,6,0,false);
g.addEdge(6,5,0,false);
g.addEdge(5,7,0,false);
g.addEdge(4,7,0,false);
// g.addEdge(7,1,0,false);
g.display();
System.out.println(hasCycle(graph));
}
}