Leetcode题547、朋友圈（Python题解）Amazon面试题

leetcode547.朋友圈

1
DFS

class Solution:
def findCircleNum(self, M: List[List[int]]) -> int:
N = len(M)
count = 0
visited = set()

def dfs(i):
for j in range(N):
if M[i][j] and j not in visited:
dfs(j)

for i in range(N):
if  i not in visited:
count += 1
dfs(i)

return count



2
BFS

class Solution(object):
def findCircleNum(self, M):
N, visited, res = len(M), set(), 0
for i in range(N):
if i not in visited:
queue = [i]
while queue:
p = queue.pop(0)
if p not in visited:
queue += [k for k, num in enumerate(M[p]) if num and k not in visited]
res += 1
return res


3

class Solution:
def findCircleNum(self, M) -> int:
father = [i for i in range(len(M))]	#首先每个点自成集合

def find(a):
if father[a] != a: father[a] = find(father[a])	#寻找每个组点的最初父结点，并做路径压缩。
return father[a]

def union(a, b):
father[find(b)] = find(a)	#b所在集合的父节点指向a，将两个集合融合。
return find(b)

for a in range(len(M)):
for b in range(a):
if M[a][b]: union(a, b)	#根据题目提供的关系进行集合融合
for i in range(len(M)): find(i)	#统计最终的集合数量就是朋友圈数量
return len(set(father))

04-27

12-29
03-21 335
07-11 141
12-28 490
11-20 1341