Cod sursa(job #3318429)

Utilizator h4rap-a1bMihail Cosor h4rap-a1b Data 28 octombrie 2025 12:34:48
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
//
// Created by h4rapa1b on 10/28/25.
//

#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

vector<vector<int> > graph;
vector<bool> visited;

void dfs(int node) {
    visited[node] = true;
    for (int neighbor: graph[node]) {
        if (!visited[neighbor]) {
            dfs(neighbor);
        }
    }
}

int count_comp(int n) {
    int componente_conexe = 0;
    for (int i = 1; i <= n; i++) {
        if (!visited[i]) {
            componente_conexe++;
            dfs(i);
        }
    }
    return componente_conexe;
}

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

    int n, m;
    fin >> n >> m;

    graph.resize(n+1);
    visited.resize(n+1, false);

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

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

    int componente_conexe = count_comp(n);
    fout << componente_conexe << endl;

    fin.close();
    fout.close();

    return 0;
}