Cod sursa(job #3151562)

Utilizator chiriacandrei25Chiriac Andrei chiriacandrei25 Data 21 septembrie 2023 20:02:26
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.68 kb
#include <fstream>
#include <vector>

using namespace std;

const int Nmax = 100005;

int n, m;
bool viz[Nmax];
vector<int> L[Nmax];

void dfs(int node) {
    viz[node] = true;
    for(int vec : L[node]) {
        if(!viz[vec]) {
            dfs(vec);
        }
    }
}

int main() {
    ifstream fin("dfs.in");
    ofstream fout("dfs.out");
    fin >> n >> m;
    while(m--) {
        int x, y;
        fin >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }
    int nr_comp = 0;
    for(int i = 1; i <= n; i++) {
        if(!viz[i]) {
            nr_comp++;
            dfs(i);
        }
    }

    fout << nr_comp;
    return 0;
}