문제
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{
static ArrayList<Integer>[] adjacent;
static boolean[] visited;
public static void dfs(int start) {
visited[start] = true;
for(int e : adjacent[start]) {
if(!visited[e])
dfs(e);
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] info = br.readLine().split("\\s");
int N = Integer.parseInt(info[0]);
int M = Integer.parseInt(info[1]);
adjacent = new ArrayList[N+1];
visited = new boolean[N+1];
for(int i=1; i<=N ; i++) {
adjacent[i] = new ArrayList<Integer>();
}
for(int i=0; i<M; i++) {
String[] strs = br.readLine().split("\\s");
int a = Integer.parseInt(strs[0]);
int b = Integer.parseInt(strs[1]);
adjacent[a].add(b);
adjacent[b].add(a);
}
int cnt = 0;
for(int i=1; i<=N; i++) {
if(!visited[i]) {
dfs(i);
++cnt;
}
}
System.out.println(cnt);
}
}
'Preparing Coding Test > Baekjoon' 카테고리의 다른 글
[Java/백준/완전 탐색] 1436번: 영화감독 숌 (0) | 2020.12.15 |
---|---|
[Java/백준/BFS] 1655번: 가운데를 말해요 (0) | 2020.11.27 |
[Java/백준/우선순위 큐] 11286번: 절댓값 힙 (0) | 2020.11.25 |
[Java/백준/우선순위 큐] 11279번: 최대 힙, 1927번: 최소 힙 (0) | 2020.11.25 |
[Java/백준/BFS] 1389번: 케빈 베이컨의 6단계 법칙 (0) | 2020.11.23 |