觉得这道题没必要用dfs + 并查集。感觉更复杂。会用拓扑排序就够了
import java.util.*;
public class Main {
public static boolean[] isVisited;
public static void main(String[] args) {
Map<Integer, List<Integer>> map = new HashMap(); // 创建图
Scanner input = new Scanner(System.in);
int n = input.nextInt();
isVisited = new boolean[n + 1];
for(int i = 1; i <= n; i++) {
map.put(i, new ArrayList<Integer>());
}
int degree[] = new int[n + 1]; // 无向图各点的度数,包含入度和出度
for(int i = 1; i <= n; i++) {
int a = input.nextInt();
int b = input.nextInt();
map.get(a).add(b);
map.get(b).add(a);
degree[a]++;
degree[b]++;
}
Queue<Integer> queue = new LinkedList();
for(int i = 1; i <= n; i++) {
if (degree[i] == 1) {
queue.add(i);
isVisited[i] = true;
}
}
while (!queue.isEmpty()) {
Integer poll = queue.poll();
for (Integer e : map.get(poll)) {
degree[e]--;
if (degree[e] == 1) {
queue.add(e);
isVisited[e] = true;
}
}
}
for(int i = 1; i <= n; i++) {
if (!isVisited[i]) {
System.out.print(i + " ");
}
}
}
}