-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDFS_Using_Iterator.java
More file actions
57 lines (56 loc) · 970 Bytes
/
Copy pathDFS_Using_Iterator.java
File metadata and controls
57 lines (56 loc) · 970 Bytes
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.LinkedList;
import java.util.Stack;
import java.util.Scanner;
class DfsUsingItertator
{
int v;
LinkedList<Integer> adj[];
public DfsUsingItertator(int v)
{
this.v=v;
adj=new LinkedList[v];
for(int i=0;i<v;i++)
{
adj[i]=new LinkedList<>();
}
}
void addEdge(int src,int dest)
{
adj[src].add(dest);
}
void dfs(int s)
{
int []visited=new int[v];
Stack<Integer> st=new Stack<Integer>();
st.push(s);
while(!st.isEmpty())
{
s=st.pop();
if(visited[s]==0)
{
System.out.print(s+" ");
visited[s]=1;
}
for(int i:adj[s])
{
if(visited[i]==0)
st.push(i);
}
}
}
public static void main(String ar[])
{
Scanner sc=new Scanner(System.in);
int v=sc.nextInt();
int e=sc.nextInt();
DfsUsingItertator graph=new DfsUsingItertator(v);
for(int i=1;i<=e;i++)
{
int src=sc.nextInt();
int dest=sc.nextInt();
graph.addEdge(src,dest);
}
int s=sc.nextInt();
graph.dfs(s);
}
}