-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloopcheck.java
59 lines (54 loc) · 1.06 KB
/
loopcheck.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
package GRAPH;
import java.util.Iterator;
import java.util.LinkedList;
public class DfsLoopCheck {
int v;
color id[];
int parent[];
LinkedList<LinkedList<Integer>> arr;
DfsLoopCheck(int v)
{
this.v=v;
id=new color[v];
arr=new LinkedList<LinkedList<Integer>>();
parent=new int[v];
for(int i=0;i<v;i++)
{
arr.add(new LinkedList<>());
id[i]=color.White;
}
}
void addEdge(int s,int d)
{
arr.get(s).add(d);
}
int dfsLoop(int start,int p)
{
id[start]=color.Grey;
parent[start]=p;
Iterator<Integer>itr=arr.get(start).iterator();
while(itr.hasNext())
{
int x=itr.next();
if(id[x]==color.White)
{
return dfsLoop(x,start);
}
else if(id[x]==color.Grey && parent[x]!=start)
{
return 1;
}
}
id[start]=color.Black;
return 0;
}
public static void main(String args[])
{
DfsLoopCheck d2=new DfsLoopCheck(6);
d2.addEdge(0, 1);
d2.addEdge(1, 2);
d2.addEdge(2, 0);
int x=d2.dfsLoop(0,-1);
System.out.println(x);
}
}