1
+ import java .util .*;
2
+
3
+ class DirectedGraph {
4
+ private int numberOfVertices ;
5
+ private List <List <Integer >> adjacencyList ;
6
+
7
+ public DirectedGraph (int vertices ) {
8
+ numberOfVertices = vertices ;
9
+ adjacencyList = new ArrayList <>(numberOfVertices );
10
+ for (int i = 0 ; i < numberOfVertices ; i ++) {
11
+ adjacencyList .add (new ArrayList <>());
12
+ }
13
+ }
14
+
15
+ public void addEdge (int source , int destination ) {
16
+ adjacencyList .get (source ).add (destination );
17
+ }
18
+
19
+ private void performTopologicalSortUtil (int vertex , boolean [] visited , Stack <Integer > stack ) {
20
+ visited [vertex ] = true ;
21
+ for (Integer neighbor : adjacencyList .get (vertex )) {
22
+ if (!visited [neighbor ]) {
23
+ performTopologicalSortUtil (neighbor , visited , stack );
24
+ }
25
+ }
26
+ stack .push (vertex );
27
+ }
28
+
29
+ public void performTopologicalSort () {
30
+ Stack <Integer > topologicalOrderStack = new Stack <>();
31
+ boolean [] visited = new boolean [numberOfVertices ];
32
+
33
+ Arrays .fill (visited , false );
34
+
35
+ for (int vertex = 0 ; vertex < numberOfVertices ; vertex ++) {
36
+ if (!visited [vertex ]) {
37
+ performTopologicalSortUtil (vertex , visited , topologicalOrderStack );
38
+ }
39
+ }
40
+
41
+ // Print the topological order
42
+ System .out .println ("Topological Sort Order:" );
43
+ while (!topologicalOrderStack .isEmpty ()) {
44
+ System .out .print (topologicalOrderStack .pop () + " " );
45
+ }
46
+ }
47
+
48
+ public static void main (String [] args ) {
49
+ DirectedGraph graph = new DirectedGraph (6 );
50
+ graph .addEdge (5 , 2 );
51
+ graph .addEdge (5 , 0 );
52
+ graph .addEdge (4 , 0 );
53
+ graph .addEdge (4 , 1 );
54
+ graph .addEdge (2 , 3 );
55
+ graph .addEdge (3 , 1 );
56
+
57
+ System .out .println ("Performing Topological Sort:" );
58
+ graph .performTopologicalSort ();
59
+ }
60
+ }
0 commit comments