July 25, 2022

323. Number of Connected Components in an Undirected Graph

323. Number of Connected Components in an Undirected Graph

Sol1. DFS

Time = O(V+E), Space = O(V+E)

class Solution {
    public int countComponents(int n, int[][] edges) {
        List<List<Integer>> adjacencyList = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adjacencyList.add(new ArrayList<>());
        }
        for (int i = 0; i < edges.length; i++) {
            adjacencyList.get(edges[i][0]).add(edges[i][1]);
            adjacencyList.get(edges[i][1]).add(edges[i][0]);
        }
        Set<Integer> visited = new HashSet<>();
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (!visited.contains(i)) {
                count++;
                dfsHelper(i, visited, adjacencyList);
            }
        }
        return count;
    }
    
    private void dfsHelper(int i, Set<Integer> visited, List<List<Integer>> adjacencyList) {
        visited.add(i);
        for (int num : adjacencyList.get(i)) {
            if (!visited.contains(num)) {
                dfsHelper(num, visited, adjacencyList);
            }
        }
    }
}

Sol2. BFS

Time = O(V+E), Space = O(V+E)

class Solution {
    public int countComponents(int n, int[][] edges) {
        List<List<Integer>> adjacencyList = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adjacencyList.add(new ArrayList<>());
        }
        for (int i = 0; i < edges.length; i++) {
            adjacencyList.get(edges[i][0]).add(edges[i][1]);
            adjacencyList.get(edges[i][1]).add(edges[i][0]);
        }
        Set<Integer> visited = new HashSet<>();
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (!visited.contains(i)) {
                count++;
                bfsHelper(i, visited, adjacencyList);
            }
        }
        return count;
    }
    
    private void bfsHelper(int i, Set<Integer> visited, List<List<Integer>> adjacencyList) {
        visited.add(i);
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(i);
        while (!queue.isEmpty()) {
            int cur = queue.poll();
            for (int num : adjacencyList.get(cur)) {
                if (!visited.contains(num)) {
                    visited.add(num);
                    queue.offer(num);
                }
            }
        }
    }
}
comments powered by Disqus