[LeetCode]Friend Circles

题目描述:

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

Example 2:

Input: 
[[1,1,0],
 [1,1,1],
 [0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, 
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.

Note:

  1. N is in range [1,200].
  2. M[i][i] = 1 for all students.
  3. If M[i][j] = 1, then M[j][i] = 1.

题目大意:

给定邻接矩阵M,求连通分量的个数。

注意:

  1. N的范围[1, 200]
  2. M[i][i] = 1
  3. 如果M[i][j] = 1,那么M[j][i] = 1

解题思路:

下面分别介绍利用并查集、深度优先搜索/广度优先搜索、Floyd-Warshall算法求解此题的过程。

解法I 并查集(Disjoint-set data structure)

并查集资料参阅:https://en.wikipedia.org/wiki/Disjoint-set_data_structure

遍历矩阵M,若M[x][y] == 1,Union(x, y)

统计未被合并(祖先等于其本身)的节点个数即为答案。

Python代码:

class Solution(object):
    def findCircleNum(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        N = len(M)
        f = range(N)

        def find(x):
            while f[x] != x: x = f[x]
            return x

        for x in range(N):
            for y in range(x + 1, N):
                if M[x][y]: f[find(x)] = find(y)
        return sum(f[x] == x for x in range(N))

解法II 深度优先搜索 / 广度优先搜索(DFS / BFS)

FloodFill 搜索 + 计数

Python代码(DFS):

class Solution(object):
    def findCircleNum(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        cnt, N = 0, len(M)
        vset = set()
        def dfs(n):
            for x in range(N):
                if M[n][x] and x not in vset:
                    vset.add(x)
                    dfs(x)
        for x in range(N):
            if x not in vset:
                cnt += 1
                dfs(x)
        return cnt

Python代码(BFS):

class Solution(object):
    def findCircleNum(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        cnt, N = 0, len(M)
        vset = set()
        def bfs(n):
            q = [n]
            while q:
                n = q.pop(0)
                for x in range(N):
                    if M[n][x] and x not in vset:
                        vset.add(x)
                        q.append(x)
        for x in range(N):
            if x not in vset:
                cnt += 1
                bfs(x)
        return cnt

解法III Floyd-Warshall 求传递闭包

Floyd-Warshall算法参阅:

https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm

Python代码:

class Solution(object):
    def findCircleNum(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        N = len(M)
        for k in range(N):
            for i in range(N):
                for j in range(N):
                    M[i][j] = M[i][j] or (M[i][k] and M[k][j])
        cnt = 0
        vset = set()
        for x in range(N):
            if x not in vset:
                cnt += 1
                for y in range(x + 1, N):
                    if M[x][y]: vset.add(y)
        return cnt

 

本文链接:http://bookshadow.com/weblog/2017/04/03/leetcode-friend-circles/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论