-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.java
More file actions
57 lines (55 loc) · 1.4 KB
/
Copy pathdfs.java
File metadata and controls
57 lines (55 loc) · 1.4 KB
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.ArrayList;
import java.util.Stack;
public class dfs {
int v;
ArrayList<Integer>[] adj;
dfs(int novtx){
v=novtx;
adj=new ArrayList[novtx];
for (int i = 0; i < novtx; i++) {
adj[i]=new ArrayList<>();
}
}
void edge(int x,int y){
adj[x].add(y);
}
void depthfs(int svtx){
boolean[] vstd= new boolean[v];
Stack<Integer> s1=new Stack<>();
s1.push(svtx);
int nod;
while(!s1.empty()){
svtx=s1.peek();
s1.pop();
for (int i = 0;i<adj[svtx].size(); i++) {
nod=adj[svtx].get(i);
if(!vstd[nod]){
s1.push(nod);
}
if(vstd[svtx]==false){
System.out.print(svtx+" ");
vstd[svtx]=true;
}
}
}
}
public static void main(String[] args) {
dfs d=new dfs(6);
d.edge(0,1);
d.edge(0,2);
d.edge(0,5);
d.edge(1,0);
d.edge(1,2);
d.edge(2,0);
d.edge(2,1);
d.edge(2,3);
d.edge(2,4);
d.edge(3,2);
d.edge(4,2);
d.edge(4,5);
d.edge(5,0);
d.edge(5,4);
System.out.println("DFS output :-");
d.depthfs(0);
}
}