|
| 1 | +package com.thealgorithms.datastructures.graphs; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Stack; |
| 6 | + |
| 7 | +/** |
| 8 | + * Topological Sorting using Depth-First Search (DFS) |
| 9 | + * |
| 10 | + * <p>Topological sorting for a Directed Acyclic Graph (DAG) is a linear ordering of vertices |
| 11 | + * such that for every directed edge u → v, vertex u comes before v in the ordering. |
| 12 | + * |
| 13 | + * <p>This algorithm uses DFS traversal to compute the topological order. It maintains a visited |
| 14 | + * set to track processed nodes and a recursion stack to detect cycles. |
| 15 | + * |
| 16 | + * <p>Time Complexity: O(V + E) where V is the number of vertices and E is the number of edges |
| 17 | + * <p>Space Complexity: O(V) for the recursion stack and data structures |
| 18 | + * |
| 19 | + * <p>Applications: |
| 20 | + * - Task scheduling with dependencies |
| 21 | + * - Build systems (e.g., makefiles) |
| 22 | + * - Course prerequisite resolution |
| 23 | + * - Compilation order in software projects |
| 24 | + * |
| 25 | + * @author Raghu0703 |
| 26 | + * @see <a href="https://en.wikipedia.org/wiki/Topological_sorting">Topological Sorting</a> |
| 27 | + */ |
| 28 | +public final class TopologicalSortDFS { |
| 29 | + |
| 30 | + private TopologicalSortDFS() { |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Performs topological sorting on a directed graph using DFS |
| 35 | + * |
| 36 | + * @param graph the adjacency list representation of the directed graph |
| 37 | + * @return a list containing vertices in topological order |
| 38 | + * @throws IllegalArgumentException if the graph contains a cycle |
| 39 | + */ |
| 40 | + public static List<Integer> topologicalSort(List<List<Integer>> graph) { |
| 41 | + if (graph == null || graph.isEmpty()) { |
| 42 | + return new ArrayList<>(); |
| 43 | + } |
| 44 | + |
| 45 | + int vertices = graph.size(); |
| 46 | + boolean[] visited = new boolean[vertices]; |
| 47 | + boolean[] recursionStack = new boolean[vertices]; |
| 48 | + Stack<Integer> stack = new Stack<>(); |
| 49 | + |
| 50 | + // Perform DFS from all unvisited vertices |
| 51 | + for (int i = 0; i < vertices; i++) { |
| 52 | + if (!visited[i]) { |
| 53 | + if (hasCycleDFS(graph, i, visited, recursionStack, stack)) { |
| 54 | + throw new IllegalArgumentException("Graph contains a cycle. Topological sort is not possible for cyclic graphs."); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + // Pop all vertices from stack to get topological order |
| 60 | + List<Integer> result = new ArrayList<>(); |
| 61 | + while (!stack.isEmpty()) { |
| 62 | + result.add(stack.pop()); |
| 63 | + } |
| 64 | + |
| 65 | + return result; |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Helper method to perform DFS and detect cycles |
| 70 | + * |
| 71 | + * @param graph the adjacency list representation of the graph |
| 72 | + * @param vertex current vertex being processed |
| 73 | + * @param visited array to track visited vertices |
| 74 | + * @param recursionStack array to track vertices in current recursion path |
| 75 | + * @param stack stack to store vertices in reverse topological order |
| 76 | + * @return true if a cycle is detected, false otherwise |
| 77 | + */ |
| 78 | + private static boolean hasCycleDFS(List<List<Integer>> graph, int vertex, boolean[] visited, boolean[] recursionStack, Stack<Integer> stack) { |
| 79 | + // Mark current node as visited and part of recursion stack |
| 80 | + visited[vertex] = true; |
| 81 | + recursionStack[vertex] = true; |
| 82 | + |
| 83 | + // Recur for all adjacent vertices |
| 84 | + List<Integer> neighbors = graph.get(vertex); |
| 85 | + if (neighbors != null) { |
| 86 | + for (Integer neighbor : neighbors) { |
| 87 | + // If neighbor is not visited, recursively check for cycles |
| 88 | + if (!visited[neighbor]) { |
| 89 | + if (hasCycleDFS(graph, neighbor, visited, recursionStack, stack)) { |
| 90 | + return true; |
| 91 | + } |
| 92 | + } else if (recursionStack[neighbor]) { |
| 93 | + // If neighbor is in recursion stack, cycle detected |
| 94 | + return true; |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + // Remove vertex from recursion stack and push to result stack |
| 100 | + recursionStack[vertex] = false; |
| 101 | + stack.push(vertex); |
| 102 | + return false; |
| 103 | + } |
| 104 | + |
| 105 | + /** |
| 106 | + * Checks if the given directed graph is a Directed Acyclic Graph (DAG) |
| 107 | + * |
| 108 | + * @param graph the adjacency list representation of the directed graph |
| 109 | + * @return true if graph is a DAG, false if it contains a cycle |
| 110 | + */ |
| 111 | + public static boolean isDAG(List<List<Integer>> graph) { |
| 112 | + if (graph == null || graph.isEmpty()) { |
| 113 | + return true; |
| 114 | + } |
| 115 | + |
| 116 | + int vertices = graph.size(); |
| 117 | + boolean[] visited = new boolean[vertices]; |
| 118 | + boolean[] recursionStack = new boolean[vertices]; |
| 119 | + |
| 120 | + for (int i = 0; i < vertices; i++) { |
| 121 | + if (!visited[i]) { |
| 122 | + if (detectCycle(graph, i, visited, recursionStack)) { |
| 123 | + return false; |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + return true; |
| 128 | + } |
| 129 | + |
| 130 | + /** |
| 131 | + * Helper method to detect cycle in a directed graph |
| 132 | + * |
| 133 | + * @param graph the adjacency list representation of the graph |
| 134 | + * @param vertex current vertex being processed |
| 135 | + * @param visited array to track visited vertices |
| 136 | + * @param recursionStack array to track vertices in current recursion path |
| 137 | + * @return true if a cycle is detected, false otherwise |
| 138 | + */ |
| 139 | + private static boolean detectCycle(List<List<Integer>> graph, int vertex, boolean[] visited, boolean[] recursionStack) { |
| 140 | + visited[vertex] = true; |
| 141 | + recursionStack[vertex] = true; |
| 142 | + |
| 143 | + List<Integer> neighbors = graph.get(vertex); |
| 144 | + if (neighbors != null) { |
| 145 | + for (Integer neighbor : neighbors) { |
| 146 | + if (!visited[neighbor]) { |
| 147 | + if (detectCycle(graph, neighbor, visited, recursionStack)) { |
| 148 | + return true; |
| 149 | + } |
| 150 | + } else if (recursionStack[neighbor]) { |
| 151 | + return true; |
| 152 | + } |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + recursionStack[vertex] = false; |
| 157 | + return false; |
| 158 | + } |
| 159 | +} |
0 commit comments