Cod sursa(job #3368406)

Utilizator badiumihneaBadiu Mihnea badiumihnea Data 14 octombrie 2026 13:33:46
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.69 kb
#include <iostream>
#include <fstream>
#include <vector>
std::ifstream f("dfs.in");
std::ofstream g("dfs.out");
std::vector<std::vector<int>> graph;
bool visited[100001];
void dfs(int node) {
    visited[node] = 1;
    for (int next:graph[node]) {
        if (!visited[next]) {
            dfs(next);
        }
    }
}
int main () {
    int n, m, nr_cc=0, x, y;
    f>>n>>m;
    graph.assign(n+1, std::vector<int>());
    for (int i=1; i<=m; i++) {
        f>>x>>y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }
    for (int i=1; i<=n; i++) {
        if (!visited[i]) {
            dfs(i);
            nr_cc++;
        }
    }
    g<<nr_cc;
    return 0;
}