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)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,880評論 0 23
  • 沾滿灰塵的衣襟, 充滿血絲的雙眼, 干裂的手,無力拖著沉重的行李。 在一望無際的雪地上, 留下了一串串或深或淺的腳...
    暮林西雨閱讀 357評論 0 1
  • 你總會遇到一個人,他會讓你放棄所有的原則,改變所有的習慣,成為你的例外…可是太晚了…而我明知不能這樣,卻控制不了自己…
    涼亭_閱讀 264評論 0 1
  • 午飯,媽媽挑起了話題,說我姑姑現在每天打兩份工。不僅要在大街上清掃垃圾。下班以后還要去網吧打掃衛生,一直工作到凌...
    六三六閱讀 286評論 2 3
  • 沒有等到后天的雨夾雪,這兩天隨手拍下了我離不開的生活:走路,吃飯, 我不太熱愛現在的生活,但我還是會慢慢接受這樣的...
    一只愛汪汪的獅子閱讀 217評論 0 4