Solution sharing


  • 0
    M
    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);
            }
        }
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.