-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopologicalSorting.java
More file actions
33 lines (27 loc) · 1.01 KB
/
TopologicalSorting.java
File metadata and controls
33 lines (27 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package graph;
import java.util.ArrayList;
import java.util.Stack;
/**
* <p>Topological sorting is used only for DAG's (Directed Acyclic Graph). <br>
* It is a linear order of vertices such that every directed edge u -> v, the vertex u comes before v in the order. </p>
* It represents dependency.
*/
public class TopologicalSorting {
public static void topSortUtil(ArrayList<ArrayList<Integer>> adj, boolean[] isVisited, int curr, Stack<Integer> st) {
isVisited[curr] = true;
for (int dest : adj.get(curr)) {
if (!isVisited[dest]) topSortUtil(adj, isVisited, dest, st);
}
st.push(curr);
}
public static void topSort(ArrayList<ArrayList<Integer>> graph, int V) {
boolean[] isVisited = new boolean[V];
Stack<Integer> st = new Stack<>();
for (int i = 0; i < V; i++) {
if (!isVisited[i]) topSortUtil(graph, isVisited, i, st);
}
while (!st.isEmpty()) {
System.out.print(st.pop() + " ");
}
}
}