Cod sursa(job #3145832)

Utilizator TomaBToma Brihacescu TomaB Data 17 august 2023 11:05:25
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <iostream>
#include <vector>

using namespace std;

const int NMAX = 1e5 + 2;
vector<int> adj[NMAX];
bool viz[NMAX];

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

    for (auto& to : adj[nod]) 
    {
        // to = adj[nod][i]
        if ( !viz[to] )
            dfs(to);
    }
}

int main(int argc, char const *argv[])
{   
    freopen("dfs.in", "r", stdin);
    freopen("dfs.out", "w", stdout);
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        cin >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }

    int nrComp = 0;
    for (int nod = 1; nod <= n; nod++)
    {
        if (!viz[nod])
        {
            dfs(nod);
            nrComp++;
        }       
    }
    
    cout << nrComp;
    return 0;
}