|
| 1 | +from typing import List |
| 2 | + |
| 3 | + |
| 4 | +class Solution: |
| 5 | + """ |
| 6 | + @param n: the number of vertices |
| 7 | + @param edges: the edges of undirected graph |
| 8 | + @return: the number of connected components |
| 9 | + """ |
| 10 | + |
| 11 | + def count_components(self, n: int, edges: List[List[int]]) -> int: |
| 12 | + # Initialize each node to be its own parent |
| 13 | + vertex_list = list(range(n)) |
| 14 | + |
| 15 | + # Helper function to find the root of a node |
| 16 | + def find(node): |
| 17 | + while vertex_list[node] != node: |
| 18 | + node = vertex_list[node] |
| 19 | + return node |
| 20 | + |
| 21 | + # Iterate through each edge and perform union |
| 22 | + for edge in edges: |
| 23 | + root1 = find(edge[0]) |
| 24 | + root2 = find(edge[1]) |
| 25 | + |
| 26 | + # If roots are different, union the components |
| 27 | + if root1 != root2: |
| 28 | + for i in range(n): |
| 29 | + if vertex_list[i] == root1: |
| 30 | + vertex_list[i] = root2 |
| 31 | + |
| 32 | + # Find all unique roots to count the number of connected components |
| 33 | + unique_roots = set(find(i) for i in range(n)) |
| 34 | + return len(unique_roots) |
| 35 | + |
| 36 | + |
| 37 | +# Test Cases |
| 38 | +solution = Solution() |
| 39 | + |
| 40 | +print(solution.count_components(4, [[0, 1], [2, 3], [3, 1]])) # Output: 1 |
| 41 | +print(solution.count_components(5, [[0, 1], [1, 2], [3, 4]])) # Output: 2 |
| 42 | +print(solution.count_components(5, [[0, 1], [1, 2], [2, 3], [3, 4]])) # Output: 1 |
| 43 | +print(solution.count_components(3, [[0, 1], [1, 2], [2, 0]])) # Output: 1 |
| 44 | +print(solution.count_components(4, [])) # Output: 4 |
| 45 | +print( |
| 46 | + solution.count_components(7, [[0, 1], [1, 2], [3, 4], [4, 5], [5, 6]]) |
| 47 | +) # Output: 2 |
0 commit comments