Cod sursa(job #2662891)

Utilizator DenisaCantuCantu Denisa DenisaCantu Data 24 octombrie 2020 19:27:30
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <iostream>
#include <fstream>
using namespace std;

ifstream f("dfs.in");
ofstream g("dfs.out");
int n, m, viz[100005], cnt;

struct nod {
    int value;
    nod *next;
} *v[100005];

void add(nod *&dest, int val) {
    nod *p;
    p = new nod;
    p->value = val;
    p->next = dest;
    dest = p;
}


void DFS(int node) {
    nod *p;
    viz[node] = 1;
    for (p = v[node]; p != NULL; p = p->next)
        if (!viz[p->value]) DFS(p->value);
}

int main() {
    f >> n >> m;
    int i, x, y;

    for (i = 1; i <= m; i++) {
        f >> x >> y;
        add(v[x], y);
        add(v[y], x);
    }
    for (i = 1; i <= n; i++)
        if (!viz[i]) {
            cnt++;
            DFS(i);
        }
    g << cnt;
    return 0;
}