Cod sursa(job #2148328)

Utilizator vladrares10Raducu Vlad-Rares vladrares10 Data 1 martie 2018 17:38:48
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>
#include <fstream>

using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");

const int NMAX = 100005;

int n, m, viz[NMAX], cnt;

typedef struct nod
{
    int info;
    nod *a;
}*pNod;

pNod v[NMAX];


void add(pNod &dest, int val);
void Read();
void DFS(int node);


int main()
{
    Read();

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

    fout << cnt;

    return 0;
}

void add(pNod &dest, int val)
{
    pNod p;
    p = new nod;
    p ->info = val;
    p ->a = dest;
    dest = p;
}

void Read()
{
    fin >> n >> m;

    for(int i = 1; i <= m; i++)
    {
        int x,y;
        fin >> x >> y;
        add(v[x],y);
        add(v[y],x);
    }
}

void DFS(int node)
{
    pNod p;
    viz[node] = 1;

    for(p = v[node]; p != NULL; p = p ->a)
        if(!viz[p ->info])
            DFS(p ->info);
}