-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathDFSTraversal.java
53 lines (43 loc) · 1.44 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
53
/*A sample java program to implement the DFS algorithm*/
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();
while (it.hasNext()) {
int n = it.next();
if (!visited[n])
DFS(n);
}
}
public static void main(String args[]) {
DFSTraversal graph = new DFSTraversal(8);
graph.insertEdge(0, 1);
graph.insertEdge(0, 2);
graph.insertEdge(0, 3);
graph.insertEdge(1, 3);
graph.insertEdge(2, 4);
graph.insertEdge(3, 5);
graph.insertEdge(3, 6);
graph.insertEdge(4, 7);
graph.insertEdge(4, 5);
graph.insertEdge(5, 2);
System.out.println("Depth First Traversal for the graph is:");
graph.DFS(0);
}
}