Post

LC 323 - Number of Connected Components in an Undirected Graph

LC 323 - Number of Connected Components in an Undirected Graph

Question

You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph.

Return the number of connected components in the graph.

Example 1:

1
2
Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2

Example 2:

1
2
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1

Constraints:

  • 1 <= n <= 2000
  • 1 <= edges.length <= 5000
  • edges[i].length == 2
  • 0 <= ai <= bi < n
  • ai != bi
  • There are no repeated edges.

Question here and solution here

Solution

concept

We can use DFS on each node to gather all nodes into a visited set. If we start on a new node and this node is not in the visited set then this node belongs to a new group. The solution is quite similar to [[261. Graph Valid Tree]] but we will calculate the number of groups.

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
    def countComponents(self, n: int, edges: List[List[int]]) -> int:
        adj_list = {i : [] for i in range(n)}
        for node_1, node_2 in edges:
            adj_list[node_1].append(node_2)
            adj_list[node_2].append(node_1)

        visited = set()

        def dfs(node, parent):
            if node in visited:
                return
            
            visited.add(node)
            for nei in adj_list[node]:
                if nei == parent:
                    continue
                dfs(nei, node)
        ans = 0
        for i in range(n):
            if i not in visited:
                ans += 1
                dfs(i, -1)
    
        return ans

Complexity

time: $O(V + E)$
space: $O(V + E)$

This post is licensed under CC BY 4.0 by the author.