法一:DFS import java.util.Scanner; public class Main { int N,M,K; boolean []black; boolean [][]edge; int []kCity,ansK; Main(){ Scanner scanner = new Scanner(System.in); N=scanner.nextInt(); M= scanner.nextInt(); K=scanner.nextInt(); black=new boolean[N+1]; edge =new boolean[N+1][N+1]; kCity=new int[K]; ansK=new int[N+1]; for (int i = 0; i < M; i++) { int h=scanner.nextInt(),l= scanner.nextInt(); edge[h][l]=true; edge[l][h]=true; }//初始化 for (int i = 0; i < K; i++) { kCity[i]=scanner.nextInt(); }//初始化 for (int i = 1; i < ansK.length; i++) { ansK[i]=-1; }//初始化 } public void ex(){ for (int i = 0; i < K; i++) { if (ansK[kCity[i]]!=-1)continue; int ans=0; for (int i1 = 1; i1 < black.length; i1++) { black[i1]=false; } black[kCity[i]]=true;//将关键点(城市)标记为遍历过的点 for (int j = 1; j < N+1; j++) { if(black[j]==false){ dfs(j); ans++; } } ansK[kCity[i]]=ans; } } public void dfs(int j){ black[j]=true; for (int i = 1; i < N+1; i++) { if(edge[i][j]&&!black[i]){ dfs(i); } } } public static void main(String[] args) { Main main = new Main(); main.ex(); for (int i : main.kCity) { System.out.println(main.ansK[i]-1); } } }