Cod sursa(job #3367542)

Utilizator vladl02Lungu Vladislav vladl02 Data 8 octombrie 2026 16:46:04
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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


int n,m;

vector<vector<int>> adj;
vector<int> viz;

void DFS(int nod){
    viz[nod] = 1;
    for(int i: adj[nod]){
        if(viz[i] == 0){
            DFS(i);
        }
        
    }
}

int main(){
    fin >> n >> m;

    adj.resize(n+5);
    viz.resize(n+5);
    int total=0;

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

    for (int i=1; i <= n; i++){
        if (viz[i] == 0){
            DFS(i);
            total++;
        }
    }
    
    cout << total;

    return 0;
}