import java.util.*; import java.util.stream.Stream; // https://en.wikipedia.org/wiki/Topological_sorting public class TopologicalSort { static void dfs(List[] graph, boolean[] used, List order, int u) { used[u] = true; for (int v : graph[u]) if (!used[v]) dfs(graph, used, order, v); order.add(u); } public static List topologicalSort(List[] graph) { int n = graph.length; boolean[] used = new boolean[n]; List order = new ArrayList<>(); for (int i = 0; i < n; i++) if (!used[i]) dfs(graph, used, order, i); Collections.reverse(order); return order; } // Usage example public static void main(String[] args) { List[] g = Stream.generate(ArrayList::new).limit(3).toArray(List[]::new); g[2].add(0); g[2].add(1); g[0].add(1); List order = topologicalSort(g); System.out.println(order); } }