Cod sursa(job #2575953)

Utilizator nTropicManescu Bogdan Constantin nTropic Data 6 martie 2020 16:26:38
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.7 kb
#include <bits/stdc++.h>

using namespace std;

const int len = 100005;
int m, n, x, y, cnt;
vector<int> g[len];
bool seen[len];

void dfs(int node) {
    seen[node] = true;
    for (auto& it : g[node])
        if (!seen[it])
            dfs(it);
}


int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

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

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

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

    cout << cnt;
}