Cod sursa(job #3333297)

Utilizator miirunaMaxim Miruna-Bianca miiruna Data 12 ianuarie 2026 19:39:19
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.7 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>

using namespace std;

//ifstream fin("dfs.in");
//ofstream fout("dfs.out");

int n,m;

int viz[100005];
typedef struct nod {
    int x;
    nod *next;
}*pNode;

pNode v[100005];

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

void dfs(int x) {
    pNode p;
    viz[x] = 1;
    for(p=v[x]; p; p=p->next) {if (!viz[p->x]) dfs(p->x);}
}

int main() {
    int c=0;
    cin>>n>>m;
    while(m--) {
        int x,y;
        cin>>x>>y;
        add(v[x],y);
        add(v[y],x);
    }
    for(int i=1;i<=n;i++) {
        if(viz[i]==0) {dfs(i);c++;}
    }
    cout<<c;
    return 0;
}