Cod sursa(job #2796592)

Utilizator truscalucaLuca Trusca truscaluca Data 8 noiembrie 2021 15:19:46
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.66 kb
#include <iostream>
#include <list>
#include <vector>

using namespace std;

const int nMax = 100005;

bool viz[nMax];
int n, m, nrComp;
list<int> v[nMax];

void dfs(int k) {
    viz[k] = true;

    for (auto x : v[k]) {
        if (!viz[x]) {
            dfs(x);
        }
    }
}

int main() {
    freopen("dfs.in", "r", stdin);
    freopen("dfs.out", "w", stdout);

    cin >> n >> m;

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

    for (int i = 1; i <= n; i++) {
        if (!viz[i]) {
            nrComp++;
            dfs(i);
        }
    }

    cout << nrComp;

    return 0;
}