Cod sursa(job #2796587)

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

using namespace std;

const int nMax = 100005;

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

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

    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 = 0; i < n; i++) {
        if (!viz[i]) {
            nrComp++;
            dfs(i);
        }
    }

    cout << nrComp;

    return 0;
}