Cod sursa(job #3317143)

Utilizator denis0bejbejan denis denis0bej Data 22 octombrie 2025 16:24:24
Problema Parcurgere DFS - componente conexe Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

vector<int> vis;
vector<vector<int>> L;

void DFS(int nod){
    vis[nod] = 1;
    for(int x : L[nod]){
        if(vis[x] == 0)
            DFS(x);
    }
}

int main() {
    int n, m;
    
    ifstream fin("dfs.in");
    ofstream fout("dfs.out");
    fin >> n >> m;
    
    for(int i = 0; i < n; i++){
        L.push_back({});
        vis.push_back(0);
    }
    for(int i = 0; i < m; i++){
        int x,y;
        fin >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }
    // for(int i = 0; i < n; i++){
    //     cout << i << ": ";
    //     for(int x : L[i])
    //         cout << x << " ";
    //     cout << endl;
    // }
    int nr = 0;
    for(int i = 0; i < n; i++){
        if(vis[i]==0){
            nr++;
            DFS(i);
        }
    }
    fout << nr;
    fin.close();
    fout.close();
    return 0;
}