import java.util.*;
import java.io.*;
public class Main {
static ArrayList<Integer>[] graph;
static boolean[] visited;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int c = Integer.parseInt(br.readLine());
int n = Integer.parseInt(br.readLine());
graph = new ArrayList[c+1];
for(int i=1; i<c+1; i++) {
graph[i] = new ArrayList<>();
}
for(int i=0; i<n;i++) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int first = Integer.parseInt(st.nextToken());
int second = Integer.parseInt(st.nextToken());
graph[first].add(second);
graph[second].add(first);
}
bw.write(solution(c)+"");
bw.flush();
br.close();
bw.close();
}
public static int solution(int c) {
visited = new boolean[c+1];
int answer = 0;
dfs(1);
for(int i=1; i<c+1;i++) {
if(visited[i]) {
answer++;
}
}
return answer-1;
}
public static void dfs(int node) {
visited[node] = true;
for(int nextN : graph[node]) {
if(!visited[nextN]) {
dfs(nextN);
}
}
}
}
- graph = new ArrayList[c+1]; 이건 그래프 배열만 만들어 놓은 것으로
사실상 graph[i] = null이 만들어진 것이다.
- for(int i=1; i<c+1; i++) {
graph[i] = new ArrayList<>();
}
이렇게 들어가줘야 graph[i] = []처럼 빈 리스트 객체를 넣어주는 거라서 꼭 필요하다.