-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCycleDetectedGraph.java
53 lines (47 loc) · 1.2 KB
/
CycleDetectedGraph.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
import java.util.*;
import java.io.*;
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[]){
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+1];
Arrays.fill(vis,false); //initialize all to false
for(int i=0;i<V;i++)
{
if(vis[i]==false)
{
if(checkForCycle(adj,i,vis))
return true;
}
}
return false;
}
}