Cod sursa(job #3295673)

Utilizator bobitoiGavriliu Tudor Paul bobitoi Data 7 mai 2025 18:03:56
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <fstream>
#include <vector>

using namespace std;

void dfs(int node, const vector<vector<int>>& connections, vector<bool>& visited) {
    visited[node] = true;
    for (int neighbor : connections[node]) {
        if (!visited[neighbor]) {
            dfs(neighbor, connections, visited);
        }
    }
}

int main() {
    ifstream input("dfs.in");
    ofstream output("dfs.out");

    int n, m;
    input >> n >> m;

    vector<vector<int>> connections(n + 1);
    for (int i = 0; i < m; ++i) {
        int x, y;
        input >> x >> y;
        connections[x].push_back(y);
        connections[y].push_back(x);
    }

    vector<bool> visited(n + 1, false);
    int counter = 0;

    for (int i = 1; i <= n; ++i) {
        if (!visited[i]) {
            dfs(i, connections, visited);
            counter++;
        }
    }

    output << counter << '\n';

    input.close();
    output.close();

    return 0;
}