Cod sursa(job #3248622)

Utilizator tMario2111Neagu Mario tMario2111 Data 12 octombrie 2024 11:53:49
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

vector<vector<int>> L;
int n, m;

vector<bool> viz;

void dfs(int node)
{
    viz[node] = true;
    for (auto v : L[node])
        if (!viz[v])
            dfs(v);
}

int main()
{
    ifstream f("dfs.in");
    f >> n >> m;
    L.resize(n + 1);
    viz.resize(n + 1, false);
    for (int i = 1; i <= m; ++i)
    {
        int a, b;
        f >> a >> b;
        L[a].push_back(b);
        L[b].push_back(a);
    }
    f.close();

    int nr_componente_conexe = 0;
    for (int i = 1; i <= n; ++i)
    {
        if (!viz[i])
        {
            ++nr_componente_conexe;
            dfs(i);
        }
    }

    ofstream g("dfs.out");
    g << nr_componente_conexe << '\n';
    g.close();

    return 0;
}