Cod sursa(job #2967184)

Utilizator stefan05Vasilache Stefan stefan05 Data 19 ianuarie 2023 10:29:46
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.79 kb
#include <fstream>
#include <algorithm>
#include <vector>

#define NMAX 100005

using namespace std;

ifstream fin("dfs.in");
ofstream fout("dfs.out");

int n, m, start; int x, y;
vector<int> mat[NMAX];
int f[NMAX]; int counter;
int i, j;
bool ok;

void dfs(int);

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

    for (start = 1; start <= n; ++start)
        if (!f[start])
        {
            counter ++;
            dfs(start);
        }

    fout <<counter<<'\n';
    fout.close();
    return 0;
}

void dfs(int vf)
{
    int  i, j;
    f[vf] = counter;
    for (j = 0; j < mat[vf].size(); ++j)
        if (!f[mat[vf][j]])
            dfs(mat[vf][j]);
}