public int countComponents(int n, int[][] edges) {
List<Set<Integer>> adjList = new ArrayList<>();
for (int i = 0; i < n; i++) {
adjList.add(new HashSet<>());
boolean[] visited = new boolean[n];
for (int[] edge : edges) {
adjList.get(edge[0]).add(edge[1]);
adjList.get(edge[1]).add(edge[0]);
for (int i = 0; i < n; i++) {
searchComponentByDFS(i, adjList, visited);
public void searchComponentByDFS(int node, List<Set<Integer>> adjList, boolean[] visited) {
for (int nextNode : adjList.get(node)) {
if (!visited[nextNode]) {
searchComponentByDFS(nextNode, adjList, visited);