Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
23539 amit.gupta 1
package com.spice.profitmandi.common.util;
2
 
3
import java.time.LocalDate;
4
import java.time.format.DateTimeFormatter;
5
import java.util.Arrays;
6
import java.util.HashMap;
7
import java.util.Iterator;
8
import java.util.LinkedList;
9
import java.util.Map;
10
import java.util.Scanner;
11
 
12
//This class represents a directed graph using adjacency list
13
//representation
14
class Graph
15
{
16
 private int V;   // No. of vertices
17
 
18
 // Array  of lists for Adjacency List Representation
19
 private LinkedList<Integer> adj[];
20
 
21
 // Constructor
22
 Graph(int v)
23
 {
24
     V = v;
25
     adj = new LinkedList[v];
26
     for (int i=0; i<v; ++i)
27
         adj[i] = new LinkedList();
28
 }
29
 
30
 //Function to add an edge into the graph
31
 void addEdge(int v, int w)
32
 {
33
     adj[v].add(w);    // Add w to v's list.
34
 }
35
 
36
 // A function used by DFS
37
 void DFSUtil(int v,boolean visited[])
38
 {
39
     // Mark the current node as visited and print it
40
     visited[v] = true;
41
     System.out.print(v+" ");
42
 
43
     // Recur for all the vertices adjacent to this vertex
44
     Iterator<Integer> i = adj[v].listIterator();
45
     while (i.hasNext())
46
     {
47
         int n = i.next();
48
         if (!visited[n])
49
             DFSUtil(n,visited);
50
     }
51
 }
52
 
53
 // The function to do DFS traversal. It uses recursive DFSUtil()
54
 void DFS()
55
 {
56
     // Mark all the vertices as not visited(set as
57
     // false by default in java)
58
     boolean visited[] = new boolean[V];
59
 
60
     // Call the recursive helper function to print DFS traversal
61
     // starting from all vertices one by one
62
     for (int i=0; i<V; ++i)
63
         if (visited[i] == false)
64
             DFSUtil(i, visited);
65
 }
66
 
67
 public static void main(String args[])
68
 {
69
     Graph g = new Graph(4);
70
 
71
     g.addEdge(0, 1);
72
     g.addEdge(0, 2);
73
     g.addEdge(1, 2);
74
     g.addEdge(2, 0);
75
     g.addEdge(2, 3);
76
     g.addEdge(3, 3);
77
 
78
     System.out.println("Following is Depth First Traversal");
79
 
80
     g.DFS();
81
 }
82
}