Cod sursa(job #3208791)

Utilizator tudorororTudor-Mihail Danila tudororor Data 1 martie 2024 02:53:39
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;

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

const int NLIM = 100005;
int N, M, componente_conexe;
vector <int> Muchii[NLIM];
bool viz[NLIM];

void DFS(int Nod)
{
    viz[Nod] = true;
    for(unsigned int i = 0; i < Muchii[Nod].size(); i++)
    {
        int Vecin = Muchii[Nod][i];
        if(!viz[Vecin])
            DFS(Vecin);
    }
}

int main()
{
    f >> N >> M;
    for(int i = 1; i <= M; i++)
    {
        int X, Y;
        f >> X >> Y;
        Muchii[X].push_back(Y);
        Muchii[Y].push_back(X);
    }
    for(int i = 1; i <= N; i++)
    {
        if(!viz[i])
        {
            componente_conexe++;
            DFS(i);
        }
    }
    g << componente_conexe;
    return 0;
}