【题目】
【代码】
思路:
这道题的本质就是求非联通子图的个数,函数给的输入是isConnected矩阵,是对称矩阵。由于是无向图,所以需要对节点是否访问给与记录,否则会陷入死循环。
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
#本质是非联通子图的个数
#无向图 矩阵对称
n=len(isConnected)
visited=[False for i in range(n)]
cnt=0
for i in range(n):
if visited[i]==False:
cnt+=1
visited[i]=True
queue=[i]
while queue:
item=queue.pop(0)
for j in range(n):
if j!=item and isConnected[item][j]==1 and not visited[j]:
visited[j]=True
queue.append(j)
return cnt
【方法2】
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
n=len(isConnected)
visited=set()
cnt=0
def dfs(x):
for i in range(n):
if x!=i and isConnected[x][i]==1 and i not in visited:
visited.add(i)
dfs(i)
for i in range(n):
if i not in visited:
visited.add(i)
dfs(i)
cnt+=1
return cnt