Python、C++、JavaScript、SQL、TypeScript の多様な LeetCode ソリューションを探索してください。面接の準備、学習、複数のプログラミング言語でのコードの練習に最適です。 Github リポジトリ リンク
You have a graph of n
nodes. You are given an integer n
and an array edges
どこ edges[i] = [ai, bi]
indicates that there is an edge between AI
そして b私
in the graph.
戻る the number of connected components in the graph.
例 1:
入力: n = 5, edges = [[0,1],[1,2],[3,4]] 出力: 2
例 2:
入力: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]] 出力: 1
制約:
1 <= n <= 2000
1 <= edges.length <= 5000
edges[i].length == 2
0 <= ai <= bi < n
ai != bi
- There are no repeated edges.
パイソン
# time complexity: O(V + E * α(n)) is the inverse Ackermann function
# space complexity: O(V)
from typing import List
class UnionFind():
def __init__(self, n):
self.parents = [i for i in range(n)]
self.rank = [0 for _ in range(n)]
def find(self, node):
while node != self.parents[node]:
node = self.parents[node]
return node
def uion(self, nodeX, nodeY):
parentX = self.find(nodeX)
parentY = self.find(nodeY)
if parentX == parentY:
return
if self.rank[parentX] > self.rank[parentY]:
self.parents[parentY] = self.parents[parentX]
elif self.rank[parentX] < self.rank[parentY]:
self.parents[parentX] = self.parents[parentY]
else:
self.parents[parentX] = self.parents[parentY]
self.rank[parentY] += 1
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
disjointUnionSet = UnionFind(n)
for startVertex, endVertex in edges:
disjointUnionSet.uion(startVertex, endVertex)
parent = set()
for i in range(n):
parent.add(disjointUnionSet.find(i))
return len(set(parent))
n = 4
edges = [[0, 1], [2, 3], [1, 2]]
print(Solution().countComponents(n, edges))