Easy to understand java solution


  • 0
    Z

    public class Solution {
    public int countComponents(int n, int[][] edges) {
    int i , E = edges.length;
    int s,t;

        List[] graph = new List[n];
        
        for(i=0;i<n;i++) {
            graph[i] = new ArrayList();
        }
        
        for(i=0;i<E;i++) {
            s = edges[i][0];
            t = edges[i][1];
            
            graph[s].add(t);
            graph[t].add(s);
        }
        
        boolean[] visited = new boolean[n];
        int ans = 0;
        
        for(i=0;i<n;i++) {
            if(dfs(i, graph, visited)) {
                ans++;
            }
        }
        
        return ans;
    }
    
    public boolean dfs(int node, List[] graph, boolean[] visited) {
        if(visited[node]) {
            return false;
        }
        visited[node] = true;
        
        for(Object object : graph[node]) {
            int next = (int)object;
            
            if(!visited[next]) {
                dfs(next, graph, visited);
            }
        }
        
        return true;
    }
    

    }


Log in to reply
 

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