拓扑排序DFS
package nkbasc;
import java.util.*;
public class AB13 {
private static List<Integer> topologicalSort(List<List<Integer>> graph, int numVertices) {
List<Integer> result = new ArrayList<>();
boolean[] visited = new boolean[numVertices];
boolean[] recursionStack = new boolean[numVertices];
boolean hasCycle = false;
for (int i = 0; i < numVertices; i++) {
if (!visited[i]) {
if (dfs(graph, i, visited, recursionStack, result)) {
hasCycle = true;
break;
}
}
}
if (hasCycle) {
System.out.println(-1);
return Collections.emptyList();
}
Collections.reverse(result);
return result;
}
private static boolean dfs(List<List<Integer>> graph, int vertex, boolean[] visited, boolean[] recursionStack, List<Integer> result) {
visited[vertex] = true;
recursionStack[vertex] = true;
for (int neighbor : graph.get(vertex)) {
if (!visited[neighbor]) {
if (dfs(graph, neighbor, visited, recursionStack, result)) {
return true;
}
} else if (recursionStack[neighbor]) {
return true;
}
}
recursionStack[vertex] = false;
result.add(vertex);
return false;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
graph.get(u).add(v);
}
List<Integer> sortedOrder = topologicalSort(graph, n);
if (!sortedOrder.isEmpty()) {
for (int i = 0; i < sortedOrder.size(); i++) {
System.out.print(sortedOrder.get(i) + 1);
if (i < sortedOrder.size() - 1) {
System.out.print(" ");
}
}
}
}
}