Cod sursa(job #3368548)

Utilizator gabs09Tofan Gabriela-Felicia gabs09 Data 15 octombrie 2026 08:22:57
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.69 kb
#include <iostream>
#include <vector>
using namespace std;

// complexitate O(n+m)

const int NMAX = 1e5;
vector<int> L[NMAX + 1];
int vis[NMAX + 1];

void dfs(int node) {
    vis[node] = 1;
    for(auto vec : L[node]) {
        if(vis[vec] == 0) {
            dfs(vec);
        }
    }
}

int main() {
    int n, m;
    cin>>n>>m;
    for(int i = 1; i<= m; i++) {
        int x, y;
        cin >> x >> y;
        L[x].push_back(x);
        L[y].push_back(x);
    }

    int cc = 0;
    for(int i = 1; i<= m; i++) {
        if(vis[i] == 0) {
            cc++;
            dfs(i);
        }
    }

    cout << "Sunt " << cc << " componente conexe";
    return 0;
}