547. Friend Circles

题目:

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

Input: 
[[1,1,0],
 [1,1,0],
 [0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. 
The 2nd student himself is in a friend circle. So return 2

思路:

1.这题的知识点其实是Union-Find,我只用了DFS的方法写了,二刷的时候还要看Union-Find的方法去解。

Python

class Solution(object):
    def findCircleNum(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        count = 0
        visited = [0] * len(M)
        for i in xrange(len(M)):
            if not visited[i]:
                visited[i] = 1
                self.dfs(M, visited, i)
                count += 1
        return count
        
    def dfs(self, M, visited, i):
        for j in xrange(len(M)):
            if M[i][j] and not visited[j]:
                visited[j] = 1
                self.dfs(M, visited, j)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,562评论 0 23
  • 沾满灰尘的衣襟, 充满血丝的双眼, 干裂的手,无力拖着沉重的行李。 在一望无际的雪地上, 留下了一串串或深或浅的脚...
    暮林西雨阅读 2,812评论 0 1
  • 你总会遇到一个人,他会让你放弃所有的原则,改变所有的习惯,成为你的例外…可是太晚了…而我明知不能这样,却控制不了自己…
    凉亭_阅读 1,769评论 0 1
  • 午饭,妈妈挑起了话题,说我姑姑现在每天打两份工。不仅要在大街上清扫垃圾。下班以后还要去网吧打扫卫生,一直工作到凌...
    六三六阅读 2,271评论 2 3
  • 没有等到后天的雨夹雪,这两天随手拍下了我离不开的生活:走路,吃饭, 我不太热爱现在的生活,但我还是会慢慢接受这样的...
    一只爱汪汪的狮子阅读 1,594评论 0 4

友情链接更多精彩内容