Cod sursa(job #3295798)

Utilizator acularrRaluca Ioana Niculescu acularr Data 8 mai 2025 15:00:13
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int maxN = 100001;
vector<int> graph[maxN];
bool visited[maxN];
int n, m;

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

int main() {
    fin >> n >> m;
    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 = 0;
    for (int i = 1; i <= n; ++i) {
        if (!visited[i]) {
            dfs(i);
            componente_conexe++;
        }
    }

    fout << componente_conexe << "\n";

    return 0;
}