-
Notifications
You must be signed in to change notification settings - Fork 397
/
cycleCheckUGBfsJava
86 lines (79 loc) · 2.36 KB
/
cycleCheckUGBfsJava
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
81
82
83
84
85
86
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
while(T-->0)
{
String[] s = br.readLine().trim().split(" ");
int V = Integer.parseInt(s[0]);
int E = Integer.parseInt(s[1]);
ArrayList<ArrayList<Integer>>adj = new ArrayList<>();
for(int i = 0; i < V; i++)
adj.add(i, new ArrayList<Integer>());
for(int i = 0; i < E; i++){
String[] S = br.readLine().trim().split(" ");
int u = Integer.parseInt(S[0]);
int v = Integer.parseInt(S[1]);
adj.get(u).add(v);
adj.get(v).add(u);
}
Solution obj = new Solution();
boolean ans = obj.isCycle(V, adj);
if(ans)
System.out.println("1");
else
System.out.println("0");
}
}
}// } Driver Code Ends
class Node {
int first;
int second;
public Node(int first, int second) {
this.first = first;
this.second = second;
}
}
class Solution
{
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;
while(!q.isEmpty())
{
int node = q.peek().first;
int par = q.peek().second;
q.remove();
for(Integer it: adj.get(node))
{
if(vis[it]==false)
{
q.add(new Node(it, node));
vis[it] = true;
}
else if(par != it) return true;
}
}
return false;
}
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;
}
}