|
| 1 | +package Topological_Sort; |
| 2 | + |
| 3 | +// Problem Statement: Topological Sort (medium) |
| 4 | +// LeetCode Question: |
| 5 | + |
| 6 | +import java.util.*; |
| 7 | + |
| 8 | +public class Problem_1_Topological_Sort { |
| 9 | + public List<Integer> sort(int vertices, int[][] edges) { |
| 10 | + List<Integer> sortedOrder = new ArrayList<>(); |
| 11 | + if (vertices <= 0) |
| 12 | + return sortedOrder; |
| 13 | + |
| 14 | + // a. Initialize the graph |
| 15 | + HashMap<Integer, Integer> inDegree = |
| 16 | + new HashMap<>(); // count of incoming edges for every vertex |
| 17 | + HashMap<Integer, List<Integer>> graph = new HashMap<>(); // adjacency list graph |
| 18 | + for (int i = 0; i < vertices; i++) { |
| 19 | + inDegree.put(i, 0); |
| 20 | + graph.put(i, new ArrayList<Integer>()); |
| 21 | + } |
| 22 | + |
| 23 | + // b. Build the graph |
| 24 | + for (int i = 0; i < edges.length; i++) { |
| 25 | + int parent = edges[i][0], child = edges[i][1]; |
| 26 | + graph.get(parent).add(child); // put the child into it's parent's list |
| 27 | + inDegree.put(child, inDegree.get(child) + 1); // increment child's inDegree |
| 28 | + } |
| 29 | + |
| 30 | + // c. Find all sources i.e., all vertices with 0 in-degrees |
| 31 | + Queue<Integer> sources = new LinkedList<>(); |
| 32 | + for (Map.Entry<Integer, Integer> entry : inDegree.entrySet()) { |
| 33 | + if (entry.getValue() == 0) |
| 34 | + sources.add(entry.getKey()); |
| 35 | + } |
| 36 | + |
| 37 | + // d. For each source, add it to the sortedOrder and subtract one from all of its |
| 38 | + // children's in-degrees if a child's in-degree becomes zero, add it to sources queue |
| 39 | + while (!sources.isEmpty()) { |
| 40 | + int vertex = sources.poll(); |
| 41 | + sortedOrder.add(vertex); |
| 42 | + // get the node's children to decrement their in-degrees |
| 43 | + List<Integer> children = graph.get(vertex); |
| 44 | + for (int child : children) { |
| 45 | + inDegree.put(child, inDegree.get(child) - 1); |
| 46 | + if (inDegree.get(child) == 0) |
| 47 | + sources.add(child); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + // if topological sort is not possible as the graph has a cycle |
| 52 | + if (sortedOrder.size() != vertices) |
| 53 | + return new ArrayList<>(); |
| 54 | + |
| 55 | + return sortedOrder; |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments