-
Notifications
You must be signed in to change notification settings - Fork 33
/
DetectCycleInGraph.java
80 lines (69 loc) · 2.15 KB
/
DetectCycleInGraph.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
74
75
76
77
78
79
80
import java.util.*;
class DetectCycleInGraph
{
static boolean checkForCycle(ArrayList<ArrayList<Integer>> adj, int s,
boolean vis[], int parent[])
{
Queue<Node> q = new LinkedList<>(); //BFS
q.add(new Node(s, -1));
vis[s] =true;
// until the queue is empty
while(!q.isEmpty())
{
// source node and its parent node
int node = q.peek().first;
int par = q.peek().second;
q.remove();
// go to all the adjacent nodes
for(Integer it: adj.get(node))
{
if(vis[it]==false)
{
q.add(new Node(it, node));
vis[it] = true;
}
// if adjacent node is visited and is not its own parent node
else if(par != it) return true;
}
}
return false;
}
// function to detect cycle in an undirected graph
public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj)
{
boolean vis[] = new boolean[V];
Arrays.fill(vis,false);
int parent[] = new int[V];
Arrays.fill(parent,-1);
for(int i=0;i<V;i++)
if(vis[i]==false)
if(checkForCycle(adj, i,vis, parent))
return true;
return false;
}
public static void main(String[] args)
{
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i < 4; i++) {
adj.add(new ArrayList < > ());
}
adj.get(1).add(2);
adj.get(2).add(1);
adj.get(2).add(3);
adj.get(3).add(2);
DetectCycleInGraph obj = new DetectCycleInGraph();
boolean ans = obj.isCycle(4, adj);
if (ans)
System.out.println("1");
else
System.out.println("0");
}
}
class Node {
int first;
int second;
public Node(int first, int second) {
this.first = first;
this.second = second;
}
}