[백준 11724] 연결 요소의 개수
Algorithm/백준(BOJ)

[백준 11724] 연결 요소의 개수

반응형

[백준 11724] 연결 요소의 개수


문제 출처 : https://www.acmicpc.net/problem/11724






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Problem11724 {
    
    static int[][] map;
    static boolean[] visited;
    static int n; // 정점 개수
    static int m; // 간선 개수
    static int count = 0;
    
    public static void dfs(int i, int n){
        visited[i] = true;
        
        for (int j = 1; j <= n ; j++) {
            if(map[i][j] == 1 && visited[j] == false){
                dfs(j, n);
            }
        }
    }
 
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        String[] str = br.readLine().split(" ");
        
        n = Integer.parseInt(str[0]);
        m = Integer.parseInt(str[1]);
        
        map = new int[n+1][n+1];
        
        int u, v;
        
        for (int i = 1; i <= m ; i++) {
            String[] arr = br.readLine().split(" ");
            
            u = Integer.parseInt(arr[0]);
            v = Integer.parseInt(arr[1]);
            
            map[u][v] = map[v][u] = 1;
        }
        
        visited = new boolean[n+1];
        
        for (int i = 1; i <= n; i++) {
            if(visited[i] == false){
                dfs(i, n);
                count++;
            }
        }
        
        System.out.println(count);
    }
 
}
 
cs


반응형