문제

방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어진다.

출력

첫째 줄에 연결 요소의 개수를 출력한다.

예제 입력 1

1
2
3
4
5
6
6 5
1 2
2 5
5 1
3 4
4 6

예제 출력 1

1
2

예제 입력 2

1
2
3
4
5
6
7
8
9
6 8
1 2
2 5
5 1
3 4
4 6
5 4
2 4
2 3

예제 출력 2

1
1

내가 푼 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.*;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<Integer>[] a = (ArrayList<Integer>[]) new ArrayList[n+1];

for(int i=1; i<=n; i++) {
a[i] = new ArrayList<Integer>();
}
//인접 리스트 채우기
for(int i=0; i<m; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
a[u].add(v);
a[v].add(u);
}
boolean[] check = new boolean[n+1];
int component = 0;
for(int i=1; i<=n; i++) {
if(check[i] == false) {
dfs(a, check, i);
component += 1;
}
}

System.out.println(component);

}

public static void dfs(ArrayList<Integer>[] a, boolean[] c, int i) {
if(c[i] == true) return;
c[i] = true;
for(int x : a[i]) {
if(c[x] == false) {
dfs(a, c, x);
}
}
}


}