방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.
첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어진다.
첫째 줄에 연결 요소의 개수를 출력한다.
6 5
1 2
2 5
5 1
3 4
4 6
2
import java.util.*;
import java.io.*;
public class Main {
static int node, line;
static boolean [] visit;
static int [][] arr;
static int cnt;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer str = new StringTokenizer(br.readLine());
node = Integer.parseInt(str.nextToken());
line = Integer.parseInt(str.nextToken());
arr = new int[node+1][node+1];
visit = new boolean[node+1];
for(int i = 1; i<=line; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
arr[a][b] = arr[b][a] = 1;
}
for(int i = 1; i<=node; i++) {
if(!visit[i]) {
bfs(i);
cnt++;
}
}
System.out.println(cnt);
br.close();
}
public static void bfs(int start) {
Queue<Integer> q = new LinkedList<>();
visit[start] = true;
q.add(start);
while(!q.isEmpty()) {
start = q.poll();
for(int i = 1; i<=node; i++) {
if(arr[start][i] ==1 && !visit[i]) {
q.add(i);
visit[i] = true;
}
}
}
}
}
단순히 숫자만 세면 되니깐 DFS, BFS 모두 이용할 수 있다.
나는 좀 더 익숙해 지고싶은(?) BFS로 풀었다.
BFS 어렵지만...아직 어렵지만 그래도 비슷한 문제 계속 풀다보니 조금 쉬워지는 것도 같다ㅎㅎㅎㅎㅎ