Cod sursa(job #2217796)

Utilizator HyperLucarioTudor Mihnea HyperLucario Data 2 iulie 2018 11:42:03
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.72 kb
#include <iostream>
#include <vector>

using namespace std;

const int N = 100001;
int n, m, nrc;

vector <int> a[N];
bool viz[N];

void cit()
{
    cin>>n>>m;

    int x, y;

    for (int i=0; i<m; i++)
    {
        cin>>x>>y;

        a[x].push_back(y);
        a[y].push_back(x);
    }
}

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

    int y;

    for (int i = 0; i < a[x].size(); i++)
    {
        y = a[x][i];
        if (!viz[y])
        {
            dfs(y);
        }
    }
}

int main()
{
    cit();

    nrc = 0;

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

    cout<<nrc;

    return 0;
}