Cod sursa(job #2388273)

Utilizator gabriel-mocioacaGabriel Mocioaca gabriel-mocioaca Data 25 martie 2019 20:56:44
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.73 kb
#include <bits/stdc++.h>

using namespace std;

#define cin in
#define cout out

vector<bool> vis;
vector<vector<int>> graph;

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

void dfs(int node){
    vis[node] = true;
    for (auto neigh : graph[node]){
        if(!vis[neigh])
            dfs(neigh);
    }
}

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);

    int n, m, x, y, cnt = 0;
    cin >> n >> m;

    graph.resize(n + 1);
    vis.resize(n + 1, false);

    while(m--){
        cin >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }

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

    cout << cnt;
}