Cod sursa(job #3230470)

Utilizator Edi_GamanGaman Eduard Ionut Edi_Gaman Data 21 mai 2024 18:25:12
Problema Parcurgere DFS - componente conexe Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.73 kb
#include <iostream>
#include <fstream>
using namespace std;

struct nod{
    int info;
    nod *leg;
}*G[1005];

bool sel[1005];
ofstream g;

void DFS(int x){
    sel[x]=true;
    for (nod *p=G[x]; p!=NULL; p=p->leg)
        if (!sel[p->info]) DFS(p->info);
}

int main()
{
    int n, m, x, y, prim;
    nod *p;
    ifstream f ("dfs.in");
    f >> n >> m;
    for (int i=1; i<=m; i++){
        f >> x >> y;
        p=new nod;
        p->info=y;
        p->leg=G[x];
        G[x]=p;
        p=new nod;
        p->info=x;
        p->leg=G[y];
        G[y]=p;
    }
    f.close();
    g.open("dfs.out");
    int nr=0;
    for (int i=1; i<=n; i++)
        if (!sel[i]) {
            nr++;
            DFS(i);
        }
    g << nr;
    g.close();
}