Preview:
#include <bits/stdc++.h>
using namespace std;

void DFS(int node, const vector<vector<int>>& S, vector<int>& V){
    V[node] = 1;
    for(int i = 0; i < S[node].size(); i++){
        if(V[S[node][i]] == 0){
            DFS(S[node][i], S, V);
        }
    }
}

int main(){
    int n,m; //n so dinh m so canh
    cin >> n >> m;
    vector<vector<int>> S(n);
    vector<int> V(n,0);
    for(int i = 0; i < m; i++){
        int x,y;
        cin >> x >> y;
        S[x].push_back(y);
        S[y].push_back(x);
    }
    
    int ans = 0;
    for(int i = 0; i < n; i++){
        if(V[i] == 0){
            DFS(i, S, V);
            ans ++;
        }
    }
    
    cout << ans;
}

downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter