Cod sursa(job #2238533)

Utilizator AndreiVisoiuAndrei Visoiu AndreiVisoiu Data 6 septembrie 2018 11:56:03
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.78 kb
#include <cstdio>

using namespace std;

const int NMAX = 100001;

bool viz[NMAX];
int n;

struct nod
{
    int x;
    nod *urm;
};
nod *v[NMAX];

void add(int vf, int x) {
    nod *q = new nod;
    q->x = x;
    q->urm = v[vf];
    v[vf] = q;
}

void dfs(int x) {
    viz[x] = 1;
    nod *p;
    for(p = v[x]; p != NULL; p = p->urm)
        if(!viz[p->x]) dfs(p->x);
}
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);
        add(x, y);
        add(y, x);
    }

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