반응형
import java.util.*;
public class Main {
public static boolean visited [];
public static int map[][];
public static int n;
public static int res=0;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
n=sc.nextInt(); //정점의 갯수
int m=sc.nextInt(); //간선의 갯수
map=new int[n+1][n+1];
visited=new boolean[n+1];
Arrays.fill(visited, false); //visited 배열을 모두 false로 초기화
for(int i=0; i<n+1;i++){
Arrays.fill(map[i], 0);
}
for(int i=0;i<m;i++) {
int a=sc.nextInt();
int b=sc.nextInt();
map[a][b]=1;
map[b][a]=1;
}
dfs(1);
System.out.println(res-1);
}
public static void dfs(int k) {
res++;
visited[k]=true;
for(int i=0;i<n+1;i++) {
if(visited[i]==false&&map[k][i]==1) {
dfs(i);
}
}
}
}
반응형
댓글