1 class Solution: 2 def bfs(self,connections,visited,l,neighbours): 3 while len(l) > 0: 4 temp = [] 5 while len(l) > 0: 6 p = l.pop() 7 if visited[p] == 0: 8 visited[p] = 1 9 if p in neighbours: 10 for q in neighbours[p]: 11 if visited[q] == 0: 12 temp.append(q) 13 if len(temp) > 0: 14 l = temp[:] 15 16 17 def makeConnected(self, n: int, connections: 'List[List[int]]') -> int: 18 m = len(connections) 19 if n - m > 1: 20 return -1#线不够用 21 visited = [0] * n 22 neighbours = {} 23 for i in range(m): 24 begin,end = connections[i][0],connections[i][1] 25 if begin not in neighbours: 26 neighbours[begin] = [end] 27 else: 28 neighbours[begin].append(end) 29 if end not in neighbours: 30 neighbours[end] = [begin] 31 else: 32 neighbours[end].append(begin) 33 34 singleparts = 0 35 for i in range(n): 36 if visited[i] == 0: 37 singleparts += 1 38 self.bfs(connections,visited,[i],neighbours) 39 40 return singleparts - 1
算法思想:BFS。
如果总的线条数量少于n-1,那么不可能将所有的节点连接在一个图中返回-1。
使用BFS遍历所有节点,计算不相连的子图个数,结果等于不相连的子图个数-1。