Cod sursa(job #3302949)

Utilizator andrei_nAndrei Nicolae andrei_n Data 12 iulie 2025 12:19:32
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.73 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("dfs.in");
ofstream fout ("dfs.out");

vector <int> v[100001];
bool viz[100001];
int n, m;

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

int main()
{
    int s;
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }

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

    fout << componente;
    return 0;
}