Cod sursa(job #3196603)

Utilizator jasminePopa Jasmine jasmine Data 24 ianuarie 2024 12:46:33
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

const int NMAX = 100000;
vector<int> G[NMAX + 1];
bool vizitat[NMAX + 1];

void DFS(int nod) {
    vizitat[nod] = true;
    for (auto vecin : G[nod]) {
        if (!vizitat[vecin]) {
            DFS(vecin);
        }
    }
}

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

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

    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x); // Deoarece graful este neorientat
    }

    int componenteConexe = 0;
    for (int i = 1; i <= n; i++) {
        if (!vizitat[i]) {
            DFS(i);
            componenteConexe++;
        }
    }

    fout << componenteConexe;

    fin.close();
    fout.close();
    return 0;
}