Cod sursa(job #3334866)

Utilizator AlexN_04Nedelcu Alex AlexN_04 Data 20 ianuarie 2026 12:25:47
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.7 kb
#include <iostream> 
#include <vector>
#include <fstream>

using namespace std;

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

vector<vector<int>> la;
vector<int> viz;

void dfs(int x) {
    viz[x] = 1;
    for (int& y : la[x]) {
        if (viz[y] == 0) {
            dfs(y);
        }
    }
}

int main() {
    int N, M, nrCompConexe = 0;

    fin >> N >> M;

    la.resize(N + 1);
    viz.assign(N + 1, 0);

    for (int i = 0; i < M; i++) {
        int x, y;
        fin >> x >> y;

        la[x].push_back(y);
        la[y].push_back(x);
    }

    for (int i = 1; i <= N; i++) {
        if (viz[i] == 0) {
            nrCompConexe++;
            dfs(i);
        }
    }

    fout << nrCompConexe << endl;
}