这题的大致意思是看看相互连通的子部分有多少个。这种题目的思想个人觉得都是用queue实现BFS的想法类似,都是把邻居先保存起来,逐层遍历。对于这题我们需要保存一个标识符,用于判断是否访问过,如果queue空了,我们再加入没有访问过的新的结点,同时计数器加一。
代码如下:
class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
num = len(M)
sign = [False for _ in range(num)]
count = 0
for ii in range(num):
if sign[ii]:
continue
count += 1
sign[ii] = True
temp_list = M[ii]
result = []
for jj in range(num):
if temp_list[jj] == 1 and sign[jj] == False:
result.append(jj)
while len(result)!=0:
index = result[0]
sign[index] = True
temp = M[index]
for kk in range(num):
if temp[kk] == 1 and sign[kk] == False:
result.append(kk)
result = result[1:]
return count