Cod sursa(job #2353318)

Utilizator andreisavulescuSavulescu Andrei andreisavulescu Data 24 februarie 2019 10:30:55
Problema Parcurgere DFS - componente conexe Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <fstream>

using namespace std;
ifstream f("dfs.in");
ofstream g("dfs.out");
int n, m, nr;
bool viz[101];

struct nod
{
    int info;
    nod *urm;
};

nod *v[101];

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

void citire()
{
    int x, y;
    f >> n >> m;
    for(int i = 1; i <= m; i++)
        {
            f >> x >> y;
            add(x, y);
            add(y, x);
        }
}

void DFS(int x)
{
    viz[x] = 1;
    for(nod *p = v[x]; p != NULL; p = p->urm)
        if(viz[p->info] == 0)
            DFS(p->info);
}

void componente_conexe()
{
    for(int i = 1; i <= n; i++)
        if(viz[i] == 0)
        {
            nr++;
            DFS(i);
        }
}

int main()
{
    citire();
    componente_conexe();
    g << nr;
    return 0;
}