Little Jay

[C++] 백준 11724번 - 연결 요소의 개수 본문

알고리즘/BOJ

[C++] 백준 11724번 - 연결 요소의 개수

Jay, Lee 2021. 8. 19. 15:44

dfs 혹은 bfs로 풀 수 있는 문제이다

이 문제를 재귀를 활용한 dfs로 풀었는데

 

graph를 먼저 채운 다음 탐색을 시작한다

문제의 1번 예제를 살펴보면

1, 2, 5가 연결되어 있는데

탐색을 할 때 1, 2, 5의 탐색이 종료되면 main 함수에 있는 for문에서

dfs를 시작할 숫자는 3이 된다

이때 연결 요소의 개수를 증가시켜주면 된다.

 

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

vector<int> a[1001];
bool check[1001];

void dfs(int node) {
    check[node] = true;
    for (int i = 0; i < a[node].size(); i++) {
        int next = a[node][i];
        if (check[next] == false) {
            dfs(next);
        }
    }
}


int main() {
    int n, m;
    cin >> n >> m;;

    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        a[u].push_back(v);
        a[v].push_back(u);
    }

    int comp = 0;

    for (int i = 1; i <= n; i++) {
        if (check[i] == false) {
            dfs(i);
            comp++;
        }
    }

    cout << comp << "\n";

    return 0;
}

'알고리즘 > BOJ' 카테고리의 다른 글

[C++] 백준 9093번 - 단어 뒤집기  (0) 2021.08.19
[C++] 백준 2606번 - 바이러스  (0) 2021.08.19
[C++] 백준 1260번 - DFS와 BFS  (0) 2021.08.19
[C++] 백준 1931번 - 회의실 배정  (0) 2021.08.18
[C++] 백준 1406번 - 에디터  (0) 2021.08.18
Comments