Cod sursa(job #2639538)

Utilizator Katherine456719Swan Katherine Katherine456719 Data 2 august 2020 16:44:05
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.65 kb
#include <bits/stdc++.h>

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

vector <int> graf[100005];
bool visited[100005];

void dfs(int node)
{
    visited[node] = true;
    for(auto x : graf[node])
        if(!visited[x])
            dfs(x);
}

int main()
{
    int n, m;
    f >> n >> m;
    while(m--)
    {
        int x, y;
        f >> x >> y;
        graf[x].push_back(y);
        graf[y].push_back(x);
    }
    int ans=0;
    for(int i = 1; i <= n; ++i)
    {
        if(visited[i] == false)
        {
            ans++;
            dfs(i);
        }
    }
    g<<ans<<" ";
    return 0;
}