Cod sursa(job #2889994)

Utilizator carmenacatrineiCarmen-Lorena Acatrinei carmenacatrinei Data 14 aprilie 2022 04:32:18
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

class N_AUD{

    vector < bool > vis;
    vector < vector < int > > muchii;

    void dfs(int node) {

        vis[node] = true;

        for (int index = 0; index < muchii[node].size(); ++index) {
            int nextNode = muchii[node][index];

            if (!vis[nextNode]) {
                dfs(nextNode);
            }
        }

    }

public:

    int numarComponenteConexe(vector < vector < int > > m) {

        int counter = 0;
        int n = m.size() - 1;

        vis.resize(n + 1, false);
        muchii.resize(n + 1);
        for (int index = 1; index <= n; ++index) {
            muchii[index] = m[index];
        }

        for (int node = 1; node <= n; ++node)
            if (!vis[node]) {
                ++counter;
                dfs(node);
            }
        return counter;

    }

};

int main()
{
    N_AUD graph;
    vector < vector < int > > muchii;
    int n, m, x, y;

    in >> n >> m;

    muchii.resize(n + 1);

    for (int index = 1; index <= m; ++index) {
        in >> x >> y;

        muchii[x].push_back(y);
        muchii[y].push_back(x);
    }

    out << graph.numarComponenteConexe(muchii);
    return 0;
}