그래프가 하나로 꽉 연결되어 있지 않고 여러 뭉텅이로 나뉘어 있을 수 있습니다.
ArrayList 배열로 그래프를 표현합니다.!visited[i]), 새로운 연결 요소를 찾은 것이므로 count를 증가시키고 DFS를 시작합니다.import java.io.*;
import java.util.*;
public class Main {
static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static boolean[] visited;
static int count = 0;
public static void main(String[] args) throws Exception {
int N = nextInt(), M = nextInt();
// 1. 인접 리스트 초기화
List<Integer>[] graph = new List[N + 1];
for (int i = 1; i <= N; i++) graph[i] = new ArrayList<>();
// 2. 간선 정보 입력 (무방향 그래프이므로 양쪽 추가)
for (int i = 0; i < M; i++) {
int u = nextInt(), v = nextInt();
graph[u].add(v);
graph[v].add(u);
}
visited = new boolean[N + 1];
// 3. 모든 노드를 순회하며 탐색되지 않은 '덩어리' 찾기
for (int i = 1; i <= N; i++) {
if (!visited[i]) {
dfs(graph, i);
count++; // DFS가 한 번 끝날 때마다 연결 요소 +1
}
}
System.out.println(count);
}
static void dfs(List<Integer>[] graph, int node) {
visited[node] = true;
for (int next : graph[node]) {
if (!visited[next]) {
dfs(graph, next);
}
}
}
static int nextInt() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return Integer.parseInt(st.nextToken());
}
}
Stack 자료구조를 이용한 반복문 DFS나 BFS를 고려해야 합니다.