547. Friend Circles
- Friend Circles python solution
题目描述
There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.
Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.
解析
题目比较容易理解,求解一共有多少朋友圈。
已知一个nxn的矩阵,其实就是邻接矩阵,元素的值为1代表两者为朋友关系。而且朋友和朋友之间可以传递,只要我们有共同好友,我们就算一个圈子的人,哈哈哈。
使用深度优先搜索的方法找到一个圈子的全部人。然后遍历每个学生,如果这个学生没有在已知的圈子内,那么再深度优先搜索这个新圈子内的所有学生,圈子数加1,同时进圈的同学要统一放在一个集合内。
class Solution:
def findCircleNum(self, M: List[List[int]]) -> int:
N=len(M)
seen=set()
def dfs(node):
for i, j in enumerate(M[node]):
if j and i not in seen:
seen.add(i)
dfs(i)
ans=0
for i in range(N):
if i not in seen:
dfs(i)
ans+=1
return ans
Reference
https://leetcode.com/problems/friend-circles/discuss/101349/Python-Simple-Explanation