깊이우선탐색(DFS)

백준 11724번: 연결 요소의 개수

cepiloth 2018. 6. 23. 16:50
반응형

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


1. 문제

방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.


2. 알고리즘

키워드 - DFS


[ Figure 1 ]

1번 TestCase 는 연결 요소가 두 개다.


[ Figure 2 ]

2 번 TestCase 에서는 모든 정점이 연결되어 있어 연결 요소는 하나다.



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
64
65
66
67
68
69
70
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <stack>
#include <cstring>
 
#define MAX_SIZE 100
#define INF 0x7fffffff
 
using namespace std;
 
int dx[4= {1-100};
int dy[4= {00-11};
 
int reverse(int x) {
    int rev = 0;
    while(x != 0){
        rev = rev*10 + x%10;
        x = x/10;
    }
    return rev;
}
 
// 전역으로 선언하면 0 으로 초기화 된다.
int board[1001][1001];
int visited[1001];
 
int n,m;
void dfs(int position) {
    visited[position] = 1;
 
    for(int i = 1; i<=n; i++) {
        if (!visited[i] && board[position][i]) {
            dfs(i);
        }
    }
}
 
int main() {
 
    std::ios::sync_with_stdio(false); cin.tie(0);
 
    cin >> n >> m;
 
    for(int i=0; i<m; i++) {
        int x, y; cin >> x >> y;
        board[x][y] = board[y][x] = 1;
    }
 
    int sol =;
    for(int i=1; i<=n; i++) {
        if (visited[i] == 0) {
            sol++;
            dfs(i);
        }
    }
 
    cout << sol << "\n";
 
    return 0;
}
 
cs

반응형