Skip to content

Commit bd8a16f

Browse files
committed
Add Topological Sort algorithm using DFS in GraphSearch
1 parent 7602f1e commit bd8a16f

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package com.thealgorithms.graphsearch;
2+
3+
import java.util.ArrayList;
4+
import java.util.Stack;
5+
6+
/**
7+
* This class implements the Topological Sort algorithm using Depth-First Search
8+
* for Directed Acyclic Graphs. It prints the nodes in a topological order.
9+
*/
10+
11+
public class TopologicalSort {
12+
/**
13+
* Main method to test the Topological Sort implementation.
14+
* Creates a sample graph and prints its topological ordering.
15+
* @param args command-line arguments(not used)
16+
*/
17+
18+
public static void main(String[] args) {
19+
int v = 6;
20+
ArrayList<ArrayList<Integer>> adjList = new ArrayList<>();
21+
for(int i=0; i<v; i++){
22+
adjList.add(new ArrayList<>());
23+
}
24+
25+
//sample DAG edges
26+
adjList.get(5).add(2);
27+
adjList.get(5).add(0);
28+
adjList.get(4).add(0);
29+
adjList.get(4).add(1);
30+
adjList.get(2).add(3);
31+
adjList.get(3).add(1);
32+
33+
topoSort(v,adjList);
34+
}
35+
36+
/**
37+
* Performs the topological sort on the given graph represented by adjacency list.
38+
* Prints the nodes in topologically sorted order.
39+
*
40+
* @param v the number of vertices in the graph
41+
* @param adjList adjacency list representing the graph
42+
*/
43+
44+
45+
public static void topoSort (int v, ArrayList<ArrayList<Integer>> adjList){
46+
boolean [] visited = new boolean[v];
47+
Stack <Integer> stack = new Stack<>();
48+
49+
for (int i = 0; i < v; i++) {
50+
if(!visited[i]){
51+
topoSortUtil(i,visited,stack,adjList);
52+
}
53+
}
54+
55+
System.out.println("Topological Sort:");
56+
while (!stack.isEmpty()){
57+
System.out.print(stack.pop()+" ");
58+
}
59+
System.out.println();
60+
}
61+
62+
/**
63+
* Utility method to perform DFS starting from a given node.
64+
* Marks nodes as visited and pushes nodes to stack after visiting all their neighbors.
65+
*
66+
* @param node the current node being visited
67+
* @param visited boolean array tracking visited nodes
68+
* @param stack stack to store the topological order
69+
* @param adjList adjacency list representing the graph
70+
*
71+
*/
72+
73+
public static void topoSortUtil(int node, boolean[] visited, Stack<Integer> stack, ArrayList<ArrayList<Integer>> adjList){
74+
visited[node] = true;
75+
76+
for(int neighbour : adjList.get(node)){
77+
if(!visited[neighbour]){
78+
topoSortUtil(neighbour,visited,stack,adjList);
79+
}
80+
}
81+
stack.push(node); // add to stack after visiting all edges
82+
}
83+
}

0 commit comments

Comments
 (0)