Skip to content

Commit 040240e

Browse files
authored
Create TopologicalSort_DFS.java
1 parent 0c08148 commit 040240e

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
//Reference - https://www.geeksforgeeks.org/topological-sorting/
2+
3+
/*Algorithms -
4+
1. Maintain a visited set and a stack to record the order of vertices
5+
2. Starting from a vertex loop through all the vertices
6+
2.1 check if the vertex is present in the visited set
7+
(i) vertex in visited set ==> continue the loop
8+
(ii) vertex not in visited set ==> explore children of the current vertex recursivley ==> in a Depth First manner
9+
Exploring a vertex implies visiting it's children. When there are no children to explore push the vertex to the stack
10+
*/
11+
12+
class topologicalSort{
13+
int vertices;
14+
ArrayList<Integer> adjList[]; //adjacency list
15+
16+
topologicalSort(int n){
17+
vertices = n;
18+
adjList = new ArrayList[n];
19+
for(int i=0;i<n;i++) adjList[i] = new ArrayList<Integer>();
20+
}
21+
22+
void topo(){
23+
boolean viisted[] = new boolean[vertices]; //keep track of visited vertices
24+
Arrays.fill(visited,false);
25+
26+
Stack<Integer> stk = new Stack<Integer>(); //keep track of the order
27+
28+
for(int i=0;i<vertices;i++){
29+
if(!visited[i]) topoUtil(i,visited,stk);
30+
}
31+
32+
//print out the topological sort
33+
while(!stk.isEmpty()){
34+
System.out.println(stk.pop());
35+
}
36+
}
37+
38+
void topoUtil(int v,boolean visited[],Stack<Integer> stk){
39+
visited[v] = true;
40+
ArrayList<Integer> neighbours = adjList[v];
41+
42+
for(int i=0 ; i<neighbours.size() ; i++){ //exploring neighbours
43+
int neighbour = neighbours.get(i);
44+
if(!visited[neighbour]) topoUtil(neighbour,visited,stk); //exploring neighbours in Depth First Manner
45+
}
46+
stk.push(v);
47+
}
48+
49+
}

0 commit comments

Comments
 (0)