Notice
Recent Posts
Recent Comments
Link
«   2024/04   »
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
Archives
Today
Total
관리 메뉴

차근차근

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

대학교/Algorithm

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

SWKo 2020. 1. 29. 00:07

0. 제목

  • 백준 11724 연결 요소의 개수
  • BOJ 11724 연결 요소의 개수
  • C++ 11724 연결 요소의 개수

1. 문제

https://www.acmicpc.net/problem/11724


2. 풀이

  • DFS, BFS 두가지 방법으로 풀 수 있다.
  • checked 배열을 N번째 index까지 검사하여 true가 아니면 탐색을 실시하고 실시할때마다 count값을 1씩 증가시켜준다. 그 count값이 연결 요소의 개수이다.

3. 코드

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
58
59
60
61
62
63
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
 
int checked[1001= {0};
vector<int> a[1001];
 
void dfs(int x);
void bfs(int start);
 
int main(int argc, const char * argv[]) {
    int N, M;
    int u, v;
    int count = 0;
    
    cin >> N >> M;
    
    for(int i = 0; i < M; i++){
        cin >> u >> v;
        a[u].push_back(v);
        a[v].push_back(u);
    }
    
    for(int i = 1; i <= N; i++){
        if(!checked[i]){
            bfs(i); //or dfs(i);
            count++;
        }
    }
    cout << count << '\n';
    
    return 0;
}
 
void dfs(int x){
    if(checked[x]) return;
    checked[x] = true;
    unsigned long size = a[x].size();
    for(int i = 0; i < size; i++){
        int y = a[x][i];
        dfs(y);
    }
}
 
void bfs(int start){
    queue<int> q;
    q.push(start);
    checked[start] = true;
    while(!q.empty()){
        int x = q.front();
        q.pop();
        unsigned long size = a[x].size();
        for(int i = 0; i < size; i++){
            int y = a[x][i];
            if(!checked[y]){
                q.push(y);
                checked[y] = true;
            }
        }
    }
}
 
 

'대학교 > Algorithm' 카테고리의 다른 글

[백준 1912] 연속합  (0) 2020.02.01
[백준 1707] 이분 그래프  (0) 2020.02.01
[백준 2750] 수 정렬하기  (0) 2020.01.28
[정렬] 버블 정렬  (0) 2020.01.28
[정렬] 선택 정렬  (0) 2020.01.28
Comments