UnionFind大法好。先把edges的数量记录下来,然后根据现有的链接,开始做UF,如果可以做成,证明这条edge是需要的,edges数量-1.反正则不做。然后遍历parents array,看有多少个cluster,条件就是其parent[node] == node.这样,求得需要的edge的数量,当我们剩余的edge数>= cluster的数量-1时,我们就求得了需要的答案,而如果小于,则说明没有足够的edge来链接全部cluster,返回-1.
class UnionFind:
def __init__(self, n):
self.rank = [0 for _ in range(n)]
self.parent = [i for i in range(n)]
def find(self, a):
if self.parent[a] != a:
self.parent[a] = self.find(self.parent[a])
return self.parent[a]
def union(self, a, b):
pa = self.find(a)
pb = self.find(b)
if pa == pb:return False
if self.rank[pa] > self.rank[pb]:
self.parent[pb] = pa
elif self.rank[pb] > self.rank[pa]:
self.parent[pa] = pb
else:
self.rank[pa] += 1
self.parent[pb] = pa
return True
class Solution:
def makeConnected(self, n: int, connections: List[List[int]]) -> int:
graph = collections.defaultdict(list)
numofedge = len(connections)
uf = UnionFind(n)
for a, b in connections:
if uf.union(a,b):
numofedge -= 1
numoflisan = 0
for idx, parent in enumerate(uf.parent):
if uf.parent[idx] == idx:
numoflisan += 1
if numofedge >= numoflisan - 1:
return min(numofedge, numoflisan - 1)
else:
return -1