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