LeetCode 547. Friend Circles 解题报告(python)

547. Friend Circles

  1. 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值