Welcome to our deep dive into Java Topological Sort! This lesson is designed for both beginners and intermediates, so let's get started. 🚀
Topological Sort is a popular algorithm used for linearizing the nodes in a directed acyclic graph (DAG) with no cycles. It's a powerful tool that helps in scheduling tasks, determining the order of prerequisites in a project, and more!
Topological Sort helps us understand the dependencies between different tasks or nodes in a graph. By linearizing the graph, we can find the order in which the tasks can be executed without causing any circular dependencies, ensuring a correct and efficient execution order.
In Java, we can implement the Topological Sort using Depth-First Search (DFS). Here's a step-by-step breakdown of the algorithm:
indegree to store the incoming edges for each node.Here's a complete, working example of the Topological Sort algorithm in Java:
import java.util.*;
class Graph {
Map<Integer, List<Integer>> adjacencyList;
Map<Integer, Integer> indegree;
Graph(int vertices) {
adjacencyList = new HashMap<>();
indegree = new HashMap<>();
for (int i = 0; i < vertices; i++) {
adjacencyList.put(i, new ArrayList<>());
indegree.put(i, 0);
}
}
void addEdge(int src, int dest) {
adjacencyList.get(src).add(dest);
indegree.put(dest, indegree.get(dest) + 1);
}
List<Integer> topologicalSort() {
List<Integer> topologicallySorted = new ArrayList<>();
List<Integer> zeroIndegreeNodes = getZeroIndegreeNodes();
while (!zeroIndegreeNodes.isEmpty()) {
int node = zeroIndegreeNodes.remove(0);
topologicallySorted.add(node);
for (int neighbor : adjacencyList.get(node)) {
if (--indegree.get(neighbor) == 0) {
zeroIndegreeNodes.add(neighbor);
}
}
}
if (topologicallySorted.size() != adjacencyList.size()) {
System.out.println("Graph contains cycles and cannot be topologically sorted.");
}
return topologicallySorted;
}
List<Integer> getZeroIndegreeNodes() {
List<Integer> zeroIndegreeNodes = new ArrayList<>();
for (int key : indegree.keySet()) {
if (indegree.get(key) == 0) {
zeroIndegreeNodes.add(key);
}
}
return zeroIndegreeNodes;
}
}Now that you've learned about Java Topological Sort, let's test your knowledge with a quiz:
Which of the following is the correct way to initialize the adjacency list and indegree map in the Graph constructor?
Keep practicing and happy coding! 🤓💻💪