import java.util.*;
import java.lang.*;
import java.io.*;

// The main method must be in a class named "Main".
class Main {
    static List<List<Integer>> g; 
    static boolean[] visited; 
    static void dfs(int v) {
        visited[v] = true;
        for (int u: g.get(v)) {
            if (!visited[u]) {
                dfs(u);
            }
        }
    }

    static int connectedComponents(int n) {
        visited = new boolean[n]; 
        int cnt = 0;
        for (int i=0; i<n; i++) {
            if (!visited[i]) {
                dfs(i);
                cnt ++ ;
            }
        }
    return cnt;
    }

    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt(), m = sc.nextInt();

        g = new ArrayList<List<Integer>>(n);

        for (int i=0; i < n; i++){
            g.add(new ArrayList<Integer>()); 
        }

        for (int i=0; i<m; i++) {
            int a = sc.nextInt()-1, b = sc.nextInt()-1;
            g.get(a).add(b);
            g.get(b).add(a);           
        }
    
        System.out.println("The number of connectedComponents is " + connectedComponents(n));

        sc.close();
    }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: