```
public class Solution {
public int countComponents(int n, int[][] edges) {
//buiild grapg matrix
int graph[][] = new int[n][n];
for(int[] edge : edges){
int x = edge[0];
int y = edge[1];
graph[x][y] = 1;
graph[y][x] = 1;
}
int islands = 0;
//build visited array
int[] visited = new int[n];
for(int i =0;i<graph.length;i++){
if(visited[i]==1)continue;
islands++;
explore(i,graph,visited);
}
return islands;
}
void explore(int node, int [][]graph, int[] visited){
if(visited[node] == 1) return;
visited[node] = 1;
for(int j=0;j<graph[node].length;j++){
if(graph[node][j] == 1){
explore(j,graph,visited);
}
}
}
```

}