-
Notifications
You must be signed in to change notification settings - Fork 397
/
cycleCheckDGDfsJava
59 lines (54 loc) · 1.63 KB
/
cycleCheckDGDfsJava
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
import java.util.*;
import java.io.*;
import java.lang.*;
class DriverClass
{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int V = sc.nextInt();
int E = sc.nextInt();
for(int i = 0; i < V+1; i++)
list.add(i, new ArrayList<Integer>());
for(int i = 0; i < E; i++)
{
int u = sc.nextInt();
int v = sc.nextInt();
list.get(u).add(v);
}
if(new Solution().isCyclic(V, list) == true)
System.out.println("1");
else System.out.println("0");
}
}
}
class Solution {
private boolean checkCycle(int node, ArrayList<ArrayList<Integer>> adj, int vis[], int dfsVis[]) {
vis[node] = 1;
dfsVis[node] = 1;
for(Integer it: adj.get(node)) {
if(vis[it] == 0) {
if(checkCycle(it, adj, vis, dfsVis) == true) {
return true;
}
} else if(dfsVis[it] == 1) {
return true;
}
}
dfsVis[node] = 0;
return false;
}
public boolean isCyclic(int N, ArrayList<ArrayList<Integer>> adj) {
int vis[] = new int[N];
int dfsVis[] = new int[N];
for(int i = 0;i<N;i++) {
if(vis[i] == 0) {
if(checkCycle(i, adj, vis, dfsVis) == true) return true;
}
}
return false;
}
}