Cod sursa(job #3213404)

Utilizator rapidu36Victor Manz rapidu36 Data 13 martie 2024 09:13:57
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <fstream>
#include <vector>

using namespace std;

const int N = 1e5;

vector <int> a[N+1];
bool viz[N+1];

void dfs(int x)
{
    viz[x] = true;
    ///parcurgem lista vecinilor lui x
    for (auto y: a[x])
    {
        if (!viz[y])
        {
            dfs(y);
        }
    }
}

int main()
{
    ifstream in("dfs.in");
    ofstream out("dfs.out");
    int n, m;
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    int nr_c = 0;
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            ++nr_c;
            dfs(i);
        }
    }
    out << nr_c << "\n";
    in.close();
    out.close();
    return 0;
}