|
| 1 | +package com.thealgorithms.graph; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Stack; |
| 6 | + |
| 7 | +/** |
| 8 | + * Implementation of Topological Sort using Depth-First Search (DFS). |
| 9 | + * |
| 10 | + * <p>Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering |
| 11 | + * of vertices such that for every directed edge u → v, vertex u comes before v |
| 12 | + * in the ordering. |
| 13 | + */ |
| 14 | +public final class TopologicalSortDFS { |
| 15 | + |
| 16 | + // Private constructor to prevent instantiation |
| 17 | + private TopologicalSortDFS() { |
| 18 | + throw new AssertionError("Cannot instantiate utility class"); |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * Performs topological sorting on a directed acyclic graph. |
| 23 | + * |
| 24 | + * @param vertices the number of vertices in the graph |
| 25 | + * @param adjacencyList the adjacency list representing the graph |
| 26 | + * @return a list containing vertices in topologically sorted order |
| 27 | + */ |
| 28 | + public static List<Integer> topologicalSort(int vertices, List<List<Integer>> adjacencyList) { |
| 29 | + boolean[] visited = new boolean[vertices]; |
| 30 | + Stack<Integer> stack = new Stack<>(); |
| 31 | + |
| 32 | + for (int i = 0; i < vertices; i++) { |
| 33 | + if (!visited[i]) { |
| 34 | + dfs(i, visited, stack, adjacencyList); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + List<Integer> result = new ArrayList<>(); |
| 39 | + while (!stack.isEmpty()) { |
| 40 | + result.add(stack.pop()); |
| 41 | + } |
| 42 | + return result; |
| 43 | + } |
| 44 | + |
| 45 | + private static void dfs(int node, boolean[] visited, Stack<Integer> stack, List<List<Integer>> adjacencyList) { |
| 46 | + visited[node] = true; |
| 47 | + for (int neighbor : adjacencyList.get(node)) { |
| 48 | + if (!visited[neighbor]) { |
| 49 | + dfs(neighbor, visited, stack, adjacencyList); |
| 50 | + } |
| 51 | + } |
| 52 | + stack.push(node); |
| 53 | + } |
| 54 | +} |
0 commit comments