LeetCode 0323. Number of Connected Components in an Undirected Graph Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0323. Number of Connected Components in an Undirected Graph

Description

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:

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

Example 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.

Solutions

Solution 1: DFS

First, we construct an adjacency list g based on the given edges, where g[i] represents all neighbor nodes of node i.

Then we traverse all nodes. For each node, we use DFS to traverse all its adjacent nodes and mark them as visited until all its adjacent nodes have been visited. In this way, we have found a connected component, and the answer is incremented by one. Then we continue to traverse the next unvisited node until all nodes have been visited.

The time complexity is O(n + m), and the space complexity is O(n + m). Where n and m are the number of nodes and edges, respectively.

PythonJavaC++GoTypeScriptJavaScript
class Solution: def countComponents(self, n: int, edges: List[List[int]]) -> int: def dfs(i: int) -> int: if i in vis: return 0 vis.add(i) for j in g[i]: dfs(j) return 1 g = [[] for _ in range(n)] for a, b in edges: g[a].append(b) g[b].append(a) vis = set() return sum(dfs(i) for i in range(n))(code-box)

Solution 2: Union-Find

We can use a union-find set to maintain the connected components in the graph.

First, we initialize a union-find set, then traverse all the edges. For each edge (a, b), we merge nodes a and b into the same connected component. If the merge is successful, it means that nodes a and b were not in the same connected component before, and the number of connected components decreases by one.

Finally, we return the number of connected components.

The time complexity is O(n + m × Î±(n)), and the space complexity is O(n). Where n and m are the number of nodes and edges, respectively, and α(n) is the inverse of the Ackermann function, which can be regarded as a very small constant.

PythonJavaC++GoTypeScript
class UnionFind: def __init__(self, n): self.p = list(range(n)) self.size = [1] * n def find(self, x): if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, a, b): pa, pb = self.find(a), self.find(b) if pa == pb: return False if self.size[pa] > self.size[pb]: self.p[pb] = pa self.size[pa] += self.size[pb] else: self.p[pa] = pb self.size[pb] += self.size[pa] return True class Solution: def countComponents(self, n: int, edges: List[List[int]]) -> int: uf = UnionFind(n) for a, b in edges: n -= uf.union(a, b) return n(code-box)

Solution 3: BFS

We can also use BFS (Breadth-First Search) to count the number of connected components in the graph.

Similar to Solution 1, we first construct an adjacency list g based on the given edges. Then we traverse all nodes. For each node, if it has not been visited, we start BFS traversal from this node, marking all its adjacent nodes as visited, until all its adjacent nodes have been visited. In this way, we have found a connected component, and the answer is incremented by one.

After traversing all nodes, we get the number of connected components in the graph.

The time complexity is O(n + m), and the space complexity is O(n + m). Where n and m are the number of nodes and edges, respectively.

PythonJavaC++GoTypeScript
class Solution: def countComponents(self, n: int, edges: List[List[int]]) -> int: g = [[] for _ in range(n)] for a, b in edges: g[a].append(b) g[b].append(a) vis = set() ans = 0 for i in range(n): if i in vis: continue vis.add(i) q = deque([i]) while q: a = q.popleft() for b in g[a]: if b not in vis: vis.add(b) q.append(b) ans += 1 return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !