from typing import List# 咱們使用並查集來作這道題,一共N臺電腦的話,至少須要n-1根線。# 並查集模板class UnionFind: def __init__(self): #記錄每個節點的父節點 self.size = 0 self.father = {} def find(self,x): """尋找根節點,路徑壓縮""" root = x while self.father[root] != None: root = self.father[root] while x != root: oraginal_father = self.father[x] self.father[x] = root x = oraginal_father return root def merge(self,x,y): """合併兩個並查集""" root_x,root_y = self.find(x),self.find(y) if root_x != root_y: self.father[root_y] = x self.size -= 1 def is_connected(self,x,y): """判斷兩個節點是否相連""" return self.find(x) == self.find(y) def add(self,x): """添加新節點""" if x not in self.father: self.father[x] = None self.size += 1class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: # 首先判斷是否知足全部電腦都相連的條件。 if len(connections) < n - 1: return -1 # 定義一個並查集。 res = UnionFind() # 將全部電腦添加到並查集中。 for i in range(n): res.add(i) # 判斷兩個電腦是否相連,也就是是否同屬於一個根節點。 # 若是不是的話,那麼咱們就將這兩個電腦相連。 # 最後就能夠求出來冗餘的連線,而後撥動他們,就能夠將全部的電腦相連了。 for nums in connections: if not res.is_connected(nums[0],nums[1]): res.merge(nums[0],nums[1]) # 由於size是總的電腦數,跟連線數不同。 return res.size - 1# A = Solution()# print(A.makeConnected(4,[[0,1],[0,2],[1,2]]))