문제
https://www.acmicpc.net/problem/11724
11724번: 연결 요소의 개수
첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어
www.acmicpc.net
코드
import java.util.*;
import java.io.*;
class Main {
public static void main(String args[]) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
ArrayList<Integer> graph [] = new ArrayList [n+1];
for(int i=0;i<=n;i++) {
graph[i] = new ArrayList<>();
}
for(int i=0;i<m;i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
graph[a].add(b);
graph[b].add(a);
}
Queue<Integer> que = new LinkedList<>();
boolean visited[] = new boolean [n+1];
int count = 0;
for(int i=1;i<=n;i++) {
if(visited[i]) continue;
count += 1;
que.add(i);
while(!que.isEmpty()) {
int cur = que.poll();
for(int next : graph[cur]) {
if(visited[next]) continue;
que.add(next);
visited[next] = true;
}
}
}
System.out.print(count);
}
}