방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.
첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어진다.
첫째 줄에 연결 요소의 개수를 출력한다.
예제 입력 1
6 5
1 2
2 5
5 1
3 4
4 6
예제 출력 1
2
예제 입력 2
6 8
1 2
2 5
5 1
3 4
4 6
5 4
2 4
2 3
예제 출력 2
1
import java.util.Scanner;
import java.util.ArrayList;
public class BJ_11724_연결요소의개수구하기 {
static boolean[] visited;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int node = sc.nextInt();
int edge = sc.nextInt();
ArrayList<Integer>[] arr = new ArrayList[node+1];
visited = new boolean[node+1];
for(int i =1; i < node+1; i++){
arr[i] = new ArrayList<>();
}
for(int i =0; i < edge; i++){
int s = sc.nextInt();
int e = sc.nextInt();
arr[s].add(e);
arr[e].add(s);
}
int count = 0;
for(int i =1; i < node+1; i++){
if(!visited[i]){
count++;
DFS(arr,i);
}
}
System.out.println(count);
}
private static void DFS(ArrayList<Integer>[] ar, int i) {
if(visited[i])
return;
visited[i] = true;
for(int v: ar[i]){
if(!visited[v]){
DFS(ar, v);
}
}
}
}
dfs와 bfs에 대한 공부가 다시 필요하다 열심히 하자
dfs 구현 부분을 재귀형태로 하니 색다른 느낌이 들고 arrayList의 구현이 까다로운 것을 잘 생각해야겠다고 느꼈다.
출처 및 참고 : 백준, Do it! 코딩테스트 자바편