1+ import java .util .ArrayList ;
2+ import java .util .Arrays ;
3+ import java .util .LinkedList ;
4+ import java .util .Queue ;
5+
6+ // CORE: if children is already visited and
7+ // is not the parent of the node then there isa cycle
8+ public class cycledetectionInUndirectedGraph {
9+ private boolean isCycle (int V , ArrayList <ArrayList <Integer >> adj ) {
10+ boolean [] visited = new boolean [V + 1 ];
11+ Arrays .fill (visited , false );
12+ for (int i = 1 ; i <= V ; i ++) {
13+ if (!visited [i ]) {
14+ if (checkForCycle (adj , i , visited ))
15+ return true ;
16+ }
17+ }
18+ return false ;
19+ }
20+
21+ static boolean checkForCycle (ArrayList <ArrayList <Integer >> adj , int s , boolean visited []) {
22+ Queue <Node > q = new LinkedList <>(); // bfs queue
23+ q .add (new Node (s , -1 )); // add source node parent of start Node is -1 <-- 0
24+ visited [s ] = true ;
25+ while (!q .isEmpty ()) {
26+ int node = q .peek ().self ;
27+ int parent = q .peek ().Parent ;
28+ q .remove ();
29+ for (Integer child : adj .get (node )) {
30+ if (!visited [child ]) {
31+ q .add (new Node (child , node ));
32+ visited [child ] = true ;
33+ } else if (child != parent ) { // child is visited and is not parent, then cycle
34+ return true ;
35+ }
36+ }
37+ }
38+ return false ;
39+
40+ }
41+
42+ // driver code
43+ public static void main (String [] args ) {
44+ ArrayList <ArrayList <Integer >> adj = new ArrayList <>();
45+ adj .add (new ArrayList <>(Arrays .asList (1 , 2 )));
46+ adj .add (new ArrayList <>(Arrays .asList (2 , 3 )));
47+ adj .add (new ArrayList <>(Arrays .asList (3 , 4 )));
48+ // adj.add(new ArrayList<>(Arrays.asList(4, 5)));
49+ cycledetectionInUndirectedGraph obj = new cycledetectionInUndirectedGraph ();
50+ System .out .println (obj .isCycle (4 , adj ));
51+ }
52+ }
53+
54+ class Node {
55+ int self ;
56+ int Parent ;
57+
58+ public Node (int self , int Parent ) {
59+ this .self = self ;
60+ this .Parent = Parent ;
61+ }
62+ }
63+
64+ class cycleDetectionUsingDSU {
65+
66+ }
0 commit comments