Cod sursa(job #2769824)

Utilizator Irina.comanIrina Coman Irina.coman Data 17 august 2021 21:46:18
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.68 kb
#include <fstream>
#include <vector>

using namespace std;

vector<int> graph[100005];
int n, m;
int vis[100005];

void dfs(int node)
{
    vis[node] = true;
    for (int i = 0; i < graph[node].size(); ++i)
    {
        int next = graph[node][i];
        if (!vis[next])
            dfs(next);
    }

}

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

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

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

    fout << cc;
}