Cod sursa(job #2237060)

Utilizator AndreiVisoiuAndrei Visoiu AndreiVisoiu Data 31 august 2018 14:54:06
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.67 kb
#include <cstdio>
#include <vector>

using namespace std;

const int NMAX = 100001;

vector<int> a[NMAX];
bool viz[NMAX];
int n;

void dfs(int x) {
    viz[x] = 1;
    for(int i = 0; i < a[x].size(); i++)
        if(!viz[a[x][i]]) dfs(a[x][i]);
}
int main()
{
    freopen("dfs.in", "r", stdin);
    freopen("dfs.out", "w", stdout);
    int m, x, y, comp = 0;
    scanf("%i %i", &n, &m);

    while(m--) {
        scanf("%i %i", &x, &y);
        a[x].push_back(y);
        a[y].push_back(x);
    }

    for(int i = 1; i <= n; i++)
        if(!viz[i]) {
            comp++;
            dfs(i);
        }
    printf("%i", comp);
    return 0;
}