Professional Documents
Culture Documents
URL:
TOPOLOGICAL SORT
DIRECTED GRAPH
directed graph.
TOPOLOGICAL SORT
DIRECTED GRAPH
Outedge: An edge pointing away or departing from a node. The nodes at the
graph.
TOPOLOGICAL SORT
TOPOLOGICAL SORT
graph (DAG) in such a way that for every directed edge U V, Then vertex U
nodes in a directed graph such that every directed edge goes from left to right.
TOPOLOGICAL SORT
TOPOLOGICAL SORT
vertices. This ordering respects the partial order defined by the directed edges.
TOPOLOGICAL SORT
TOPOLOGICAL SORT
tasks that have dependencies. If task B depends on task A, then A comes before B
Search (DFS) algorithm. The idea is to visit a node and mark it as visited before
exploring its neighbors. The linear order of visiting nodes gives the topological
order.
TOPOLOGICAL SORT
TOPOLOGICAL SORT
5. Multiple Solutions: It's important to note that a DAG may have more than one
valid topological ordering. The crucial aspect is the relative order of vertices
EXAMPLE
TOPOLOGICAL SORT
EXAMPLE
TOPOLOGICAL SORT
EXAMPLE
TOPOLOGICAL SORT
EXAMPLE
TOPOLOGICAL SORT
KAHN’S ALGORITHM
Auxiliary variables:
A queue.
TOPOLOGICAL SORT
KAHN’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
KAHN’S ALGORITHM
Actual steps:
Enqueue the vertices with the in-degree of 0.
1. Dequeue a vertex.
KAHN’S ALGORITHM
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 HashMap<>(); List<Integer> order = new 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 : adjacencyList.get(u)) {
this.adjacencyList.get(u).add(v); totalIndegree[i]--;
}
public void topologicalSort() { if (totalIndegree[i] == 0) {
int[] totalIndegree = new int[vertices]; queue.add(i);
for (int i = 0; i < vertices; i++) { }
for (int j : adjacencyList.get(i)) { }
totalIndegree[j]++; visitedNodes++;
}} }
TOPOLOGICAL SORT
KAHN’S ALGORITHM
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 QUESTION
directed acyclic graph (DAG) in such a way that for every directed edge
https://learn.codemithra.com