-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dfs.java
57 lines (53 loc) · 923 Bytes
/
Dfs.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
import java.util.Iterator;
import java.util.LinkedList;
enum color {
White, Grey, Black;
}
public class DFS {
int v;
color id[];
LinkedList<LinkedList<Integer>> arr;
DFS(int v)
{
int i;
this.v=v;
id=new color[v];
arr=new LinkedList<LinkedList<Integer>>();
for(i=0;i<v;i++)
{
arr.add(new LinkedList<Integer>());
id[i]=color.White;
}
}
void addEdge(int s,int d)
{
arr.get(s).add(d);
}
void dfs(int s)
{
id[s]=color.Grey;
Iterator<Integer> i=arr.get(s).iterator();
while(i.hasNext())
{
int x=i.next();
if(id[x]==color.White)
{
dfs(x);
}
}
System.out.println(s);
id[s]=color.Black;
}
public static void main(String args[])
{
DFS d=new DFS(6);
d.addEdge(0, 1);
d.addEdge(1, 0);
d.addEdge(0, 4);
d.addEdge(4, 3);
d.addEdge(4, 2);
d.addEdge(4, 5);
d.addEdge(3, 5);
d.dfs(0);
}
}