Skip to content

Commit b3d0fa3

Browse files
committed
[Silver II] Title: 연결 요소의 개수, Time: 488 ms, Memory: 116684 KB -BaekjoonHub
1 parent e31fc92 commit b3d0fa3

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# [Silver II] 연결 요소의 개수 - 11724
2+
3+
[문제 링크](https://www.acmicpc.net/problem/11724)
4+
5+
### 성능 요약
6+
7+
메모리: 116684 KB, 시간: 488 ms
8+
9+
### 분류
10+
11+
그래프 이론, 그래프 탐색, 너비 우선 탐색, 깊이 우선 탐색
12+
13+
### 제출 일자
14+
15+
2025년 8월 1일 17:48:32
16+
17+
### 문제 설명
18+
19+
<p>방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.</p>
20+
21+
### 입력
22+
23+
<p>첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어진다.</p>
24+
25+
### 출력
26+
27+
<p>첫째 줄에 연결 요소의 개수를 출력한다.</p>
28+
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import java.util.*;
2+
import java.io.*;
3+
4+
public class Main {
5+
static int N, M;
6+
static int[][] graph;
7+
static boolean[] visited;
8+
static int count=0;
9+
10+
public static void main(String[] args) throws IOException{
11+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
12+
StringTokenizer st = new StringTokenizer(br.readLine());
13+
14+
N = Integer.parseInt(st.nextToken());
15+
M = Integer.parseInt(st.nextToken());
16+
17+
graph = new int[N+1][N+1];
18+
visited = new boolean[N+1];
19+
20+
for(int i=0; i<M; i++){
21+
st = new StringTokenizer(br.readLine());
22+
int u = Integer.parseInt(st.nextToken());
23+
int v = Integer.parseInt(st.nextToken());
24+
25+
graph[u][v] = 1;
26+
graph[v][u] = 1;
27+
}
28+
29+
for(int i=1; i<N+1; i++){
30+
if(!visited[i]){
31+
dfs(i);
32+
count++;
33+
}
34+
}
35+
36+
System.out.println(count);
37+
}
38+
39+
public static void dfs(int x){
40+
visited[x] = true;
41+
42+
for(int i=1; i<=N; i++){
43+
if(graph[x][i] == 1 && !visited[i]){
44+
dfs(i);
45+
}
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)