Cod sursa(job #3333754)

Utilizator repzcuOprescu Andrei repzcu Data 15 ianuarie 2026 02:13:56
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <vector>
#include <fstream>
using namespace std;

ifstream f("dfs.in");
ofstream g("dfs.out");

vector<vector<int>> adj;
vector<bool> viz;

void dfs(int nod)
{
    viz[nod] = true;

    for (int vecin : adj[nod])
    {
        if (!viz[vecin])
        {
            dfs(vecin);
        }
    }
}

int main()
{
    int n, m;
    f >> n >> m;

    adj.resize(n + 1);
    viz.assign(n + 1, false);

    int x, y;
    while (m--)
    {
        f >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x); // graf neorientat
    }

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

    g << componente;

    return 0;
}