1 8
1 8
TOPOLOGICAL SORT
DIRECTED GRAPH
Auxiliary variables:
⮚ A queue.
TOPOLOGICAL SORT
KHAN’S ALGORITHM
Pre-processing:
Calculate the in-degree of each vertex of the graph and store them
in the array “temp”.
INDEGREE A
TOPOLOGICAL SORT
KHAN’S ALGORITHM
Actual steps:
Enqueue the vertices with the in-degree of 0.
While the queue is not empty:
1. Dequeue a vertex.
2. Add this vertex to the result.
3. Increment the “visited” variable by 1.
4. Decrement the in-degree of all its neighboring vertices by 1 in
the array “temp”.
5 Enqueue the neighboring vertices with the in-degree of 0.
If the value of the “visited” variable is equal to the number of
vertices in the graph, then the graph is indeed directed and
acyclic
and the result will contain the topological sort for the
graph.
KHAN’S ALGORITHM TOPOLOGICAL SORT
import java.util.*; Queue<Integer> queue = new LinkedList<>();
class Graph { for (int i = 0; i < vertices; i++) {
private Map<Integer, List<Integer>> if (totalIndegree[i] == 0) {
adjacencyList; queue.add(i);
private int vertices; }
public Graph(int vertices) { }
this.vertices = vertices; int visitedNodes = 0;
this.adjacencyList = new List<Integer> order = new
HashMap<>(); ArrayList<>();
for (int i = 0; i < vertices; i++) {
this.adjacencyList.put(i, new while (!queue.isEmpty()) {
ArrayList<>()); int u = queue.poll();
} order.add(u);
}
public void createEdge(int u, int v) { for (int i :
this.adjacencyList.get(u).add(v); adjacencyList.get(u)) {
} totalIndegree[i]--;
public void topologicalSort() {
int[] totalIndegree = new if (totalIndegree[i] == 0) {
int[vertices]; queue.add(i);
for (int i = 0; i < vertices; i++) { }
for (int j : }
adjacencyList.get(i)) { visitedNodes++;
totalIndegree[j]++; }
KHAN’S ALGORITHM TOPOLOGICAL SORT
if (visitedNodes != vertices) {
System.out.println("There's a cycle present in the Graph.\nGiven graph is not
DAG");
} else {
System.out.println(order);
}
}
graph.topologicalSort();
}
}
INTERVIEW QUESTIONS