问题描述
第一版代码:
主要是解决了无向图和孤立点的特殊情况,根据孤立点个数和最大连通子图数来计算需要的边数。虽然结果是正确的,但是超时了
import collections
class Solution:
def makeConnected(self, n: int, connections):
length = len(connections)
if length<n-1:
return -1
cluster_num = 0
checked = collections.deque()
while connections:
to_check = collections.deque([connections[0][0]])
while to_check:
start = to_check.popleft()
checked += [start]
i = 0
while i < length:
[x,y] = connections[i]
if x == start or y==start:
del connections[i]
length -= 1
if x == start:
if y not in to_check and y not in checked:
to_check.append(y)
else:
if x not in to_check and x not in checked:
to_check.append(x)
else:
i += 1
cluster_num += 1
return cluster_num-1+(n-len(checked))
n = 12
connections = [[1,5],[1,7],[1,2],[1,4],[3,7],[4,7],[3,5],[0,6],[0,1],[0,4],[2,6],[0,3],[0,2]]
print(Solution().makeConnected(n,connections))
于是撰写第二版代码
用这种递归算法,虽然结果是一样的,但是速度快了不少
LeetCode代码:
class Solution:
def makeConnected(self, n: int, connections: List[List[int]]) -> int:
if len(connections)<n-1:
return -1
G = [set() for i in range(n)]
for i,j in connections:
G[i].add(j)
G[j].add(i)
seen = [0]*n
def dfs(x):
if seen[x]:
return 0
seen[x]=1
for i in G[x]:
dfs(i)
return 1
return sum(dfs(i) for i in range(n))-1
运行结果: