-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDFS.java
More file actions
67 lines (57 loc) · 1.26 KB
/
Copy pathDFS.java
File metadata and controls
67 lines (57 loc) · 1.26 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
58
59
60
61
62
63
64
65
66
67
import java.util.*;
import java.io.*;
class Graph
{
int Vertices;
LinkedList<Integer> lst[];
Graph(int v)
{
Vertices=v;
lst=new LinkedList[v];
for(int i=0;i<v;i++)
{
lst[i]=new LinkedList<Integer>();
}
}
void add_edge(int u,int v)
{
lst[u].add(v);
}
void dfs_utils(int v,boolean visited[])
{
visited[v]=true;
System.out.print(v+"->");
Iterator<Integer> i=lst[v].listIterator();
while(i.hasNext())
{
int n=i.next();
if (!visited[n])
{
dfs_utils(n,visited);
}
}
}
void dfs(int v)
{
boolean visited[]=new boolean[Vertices];
dfs_utils(v,visited);
}
}
public class DFS
{
public static void main(String[]args)
{
Scanner S=new Scanner((System.in));
System.out.println("no. of vertices");
int v=S.nextInt();
System.out.println("Enter the no. of edges");
int edge=S.nextInt();
Graph G=new Graph(v);
for(int i=0;i<edge;i++)
{
G.add_edge(S.nextInt(),S.nextInt());
}
System.out.println("vertex for dfs");
G.dfs(S.nextInt());
}
}