Cod sursa(job #3295155)

Utilizator Cristina_Micu0731Micu Alexandra Cristina Cristina_Micu0731 Data 2 mai 2025 19:30:32
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#include <vector>
using namespace std;

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

int n, m;
vector<vector<int>> adj;
vector<bool> visited;

// DFS clasic – marchez componenta curentă
void dfs(int node) {
    visited[node] = true;
    for (int neigh : adj[node]) {
        if (!visited[neigh]) {
            dfs(neigh);
        }
    }
}

// Determină numărul componentelor conexe
int numarComponenteConexe() {
    int componente = 0;

    for (int node = 1; node <= n; ++node) {
        if (!visited[node]) {
            dfs(node);
            ++componente;
        }
    }

    return componente;
}

int main() {
    fin >> n >> m;
    adj.resize(n + 1);
    visited.resize(n + 1, false);

    for (int i = 0; i < m; ++i) {
        int x, y;
        fin >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x); // pentru graf neorientat
    }

    int rezultat = numarComponenteConexe();
    fout << rezultat << "\n";

    return 0;
}