Cod sursa(job #3295796)

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

using namespace std;

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() {
    ifstream fin("dfs.in");
    ofstream fout("dfs.out");

    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;
}