| 1 | import java.util.*; |
| 2 | |
| 3 | class DFSTraversal { |
| 4 | private LinkedList<Integer> adj[]; /* adjacency list representation */ |
| 5 | private boolean visited[]; |
| 6 | |
| 7 | /* Creation of the graph */ |
| 8 | DFSTraversal(int V) /* 'V' is the number of vertices in the graph */ |
| 9 | { |
| 10 | adj = new LinkedList[V]; |
| 11 | visited = new boolean[V]; |
| 12 | |
| 13 | for (int i = 0; i < V; i++) |
| 14 | adj[i] = new LinkedList<Integer>(); |
| 15 | } |
| 16 | |
| 17 | /* Adding an edge to the graph */ |
| 18 | void insertEdge(int src, int dest) { |
| 19 | adj[src].add(dest); |
| 20 | } |
| 21 | |
| 22 | void DFS(int vertex) { |
| 23 | visited[vertex] = true; /* Mark the current node as visited */ |
| 24 | System.out.print(vertex + " "); |
| 25 | |
| 26 | // Iterator<Integer> it = adj[vertex].listIterator(); |
| 27 | ListIterator<Integer> ti = adj[vertex].listIterator(); |
| 28 | while (ti.hasNext()) { |
| 29 | int n = ti.next(); |
| 30 | if (!visited[n]) |
| 31 | DFS(n); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | public static void main(String args[]) { |
| 36 | Scanner sc = new Scanner(System.in); |
| 37 | System.out.println("Enter number of vertices"); |
| 38 | int ve = sc.nextInt(); |
| 39 | DFSTraversal graph = new DFSTraversal(ve); |
| 40 | System.out.println("Enter number of edges"); |
| 41 | int e = sc.nextInt(); |
| 42 | for (int i = 0; i < e; i++) { |
| 43 | System.out.println("Enter starting vertex of the edge " + i); |
| 44 | int u = sc.nextInt(); |
| 45 | System.out.println("Enter ending vertex of the edge " + i); |
| 46 | int v = sc.nextInt(); |
| 47 | graph.insertEdge(u, v); |
| 48 | } |
| 49 | System.out.println("Depth First Traversal for the graph is:"); |
| 50 | graph.DFS(0); |
| 51 | } |
| 52 | } |
nothing calls this directly
no outgoing calls
no test coverage detected