forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFSTraversal.java
52 lines (45 loc) · 1.6 KB
/
DFSTraversal.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
import java.util.*;
class DFSTraversal {
private LinkedList<Integer> adj[]; /* adjacency list representation */
private boolean visited[];
/* Creation of the graph */
DFSTraversal(int V) /* 'V' is the number of vertices in the graph */
{
adj = new LinkedList[V];
visited = new boolean[V];
for (int i = 0; i < V; i++)
adj[i] = new LinkedList<Integer>();
}
/* Adding an edge to the graph */
void insertEdge(int src, int dest) {
adj[src].add(dest);
}
void DFS(int vertex) {
visited[vertex] = true; /* Mark the current node as visited */
System.out.print(vertex + " ");
// Iterator<Integer> it = adj[vertex].listIterator();
ListIterator<Integer> ti = adj[vertex].listIterator();
while (ti.hasNext()) {
int n = ti.next();
if (!visited[n])
DFS(n);
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of vertices");
int ve = sc.nextInt();
DFSTraversal graph = new DFSTraversal(ve);
System.out.println("Enter number of edges");
int e = sc.nextInt();
for (int i = 0; i < e; i++) {
System.out.println("Enter starting vertex of the edge " + i);
int u = sc.nextInt();
System.out.println("Enter ending vertex of the edge " + i);
int v = sc.nextInt();
graph.insertEdge(u, v);
}
System.out.println("Depth First Traversal for the graph is:");
graph.DFS(0);
}
}