728x90
import java.util.*;
import java.lang.*;
import java.io.*;
// The main method must be in a class named "Main".
class Main {
static int N, M; // 정점, 간선 개수
static ArrayList<Integer>[] adjList; // 인근 노드
static boolean[] visited; // 노드 방문여부
static int cnt; //연결 요소 개수
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
// 정점, 간선 개수 입력받기
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
adjList = new ArrayList[N+1]; // 노드 1번부터 시작
for(int i=1; i<=N; i++){
adjList[i] = new ArrayList<>();
}
visited = new boolean[N+1];
// 간선 입력받기
for(int i=1; i<=M; i++){
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
// 방향 없는 그래프
adjList[u].add(v);
adjList[v].add(u);
}
//bfs 탐색으로 연결 요소 구하기
for(int i=1; i<=N; i++){
if(visited[i]){ // 이미 방문한 노드 제외
continue;
}
bfs(i);
cnt++;
}
// 결과 출력
System.out.println(cnt);
} //main
static void bfs(int start){
for(int n : adjList[start]){
if(visited[n]){
continue;
}
visited[n] = true;
bfs(n);
}
}
}
'Algorithm > Baekjoon' 카테고리의 다른 글
[백준 2178] Java - 공백 없는 정수 입력받기 (0) | 2025.02.26 |
---|---|
[백준 1260] Java - dfs, bfs / 가능한 작은 정점 방문하는 경우 (1) | 2025.02.25 |
[백준 11286] Java - 우선순위 큐 정렬 기준 설정법 (0) | 2025.02.24 |
[백준 10986] Java 나머지 (0) | 2025.01.10 |
[백준 11660] Java 구간 합 구하기 5 / 2차원 구간 합 배열 (0) | 2025.01.10 |