LeetCode 323: Number of Connected Components in an Undirected Graph

LeetCode 323 Solution Explanation

Explanation:

To solve this problem, we can use a graph traversal technique such as Depth First Search (DFS) or Breadth First Search (BFS) to find connected components in the given undirected graph. We will start the traversal from each unvisited node and mark all the nodes reachable from it. Each connected component will be identified by a separate traversal from an unvisited node.

Here are the steps for the algorithm:

  1. Create an adjacency list representation of the graph.
  2. Initialize a set to keep track of visited nodes.
  3. Initialize a variable to count the number of connected components.
  4. Iterate through all the nodes in the graph.
  5. For each unvisited node, perform a DFS or BFS traversal to mark all nodes reachable from it as visited. Increment the count of connected components.
  6. Return the count of connected components.

Time Complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph. Space Complexity: O(V), where V is the number of vertices in the graph.

:

LeetCode 323 Solutions in Java, C++, Python

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

Interactive Code Editor for LeetCode 323

Improve Your LeetCode 323 Solution

Use the editor below to refine the provided solution for LeetCode 323. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems