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

一个班级有N个学生,他们中的一些相互之间是朋友,朋友关系可以传递。如果A和B是直接好友,B和C是直接好友,那么即使A和C是间接好友,他们三人属于一个朋友圈。朋友圈是由直接好友和间接好友构成。给一个N * N的矩阵M表示学生之间的朋友关系。M[i][j] = 1表示学生i和学生j是直接朋友,否则不是。输出学生中的朋友圈个数。

思路:遍历矩阵里的点,如果是1,就找出和他是朋友的点和朋友的朋友的点,标记好。最后找出朋友圈的个数。

解法1: DFS

解法2: BFS

解法3: Union Find

解法4: 并查集(Disjoint-set data structure) 把有有关系的人放到一个集合里,然后计算集合的个数。

Java: DFS

public class Solution {
    public int findCircleNum(int[][] M) {
        int res = 0;
        int[] visited = new int[M.length];
        for (int i = 0; i < M.length; i++) {
            if (visited[i] == 0) {
                res++;
                dfs(M, visited, i);
            }
        }
        return res;
    }
    
    private void dfs(int[][] M, int[] visited, int i) {
        visited[i] = 1;
        for (int j = 0; j < M.length; j++) {
            if (M[i][j] == 1 && visited[j] == 0) {
                dfs(M, visited, j);
            }
            
        }
    }
}

Java: BFS

Queue<Integer> q = new LinkedList<>();  
public void bfs(int[][] M, int[] visited, int i) {  
    // visit[i];  
    q.offer(i);  
    visited[i] = 1;  
    while (!q.isEmpty()) {  
        int node = q.poll();  
        for (int j = 0; j < M.length; j++) {  
            // 未被访问过且是邻接点,注意是node的邻接点  
            if (visited[j] == 0 && M[node][j] == 1) {  
                // visit[j];  
                q.offer(j);  
                visited[j] = 1;  
            }  
        }  
    }  
  
}  
public int findCircleNum(int[][] M) {  
    int[] visited = new int[M.length];  
    int count = 0;  
    for (int i = 0; i < M.length; i++) {  
        if (visited[i] == 0) {  
            bfs(M, visited, i);  
            count++;  
        }  
    }  
    return count;  
}   

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 

Python: DFS

class Solution(object):
    def findCircleNum(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        res = 0
        hm = dict()
        for i in xrange(len(M)):
            for j in xrange(len(M)):
                group = hm.setdefault(i, set())
                if M[i][j] == 1:
                    group.add(j)

        allNodes = set()
        for i in xrange(len(M)):
            allNodes.add(i)
        while len(allNodes) != 0:
            res += 1
            root = None
            for node in allNodes:
                root = node
                break
            self.dfs(root, set(), allNodes, hm)
            
        return res        
        
    def dfs(self, root, visited, allNodes, hm):
        visited.add(root)
        allNodes.discard(root)
        unvisited = set()
        for node in hm.get(root):
            if node not in visited:
                unvisited.add(node)
        for node in unvisited:
            self.dfs(node, visited, allNodes, hm)  

Python: Union Find

class Solution(object):
    def findCircleNum(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """

        class UnionFind(object):
            def __init__(self, n):
                self.set = range(n)
                self.count = n
        
            def find_set(self, x):
               if self.set[x] != x:
                   self.set[x] = self.find_set(self.set[x])  # path compression.
               return self.set[x]
        
            def union_set(self, x, y):
                x_root, y_root = map(self.find_set, (x, y))
                if x_root != y_root:
                    self.set[min(x_root, y_root)] = max(x_root, y_root)
                    self.count -= 1

        circles = UnionFind(len(M))
        for i in xrange(len(M)):
            for j in xrange(len(M)):
                if M[i][j] and i != j:
                    circles.union_set(i, j)
        return circles.count

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)) 

C++: DFS

class Solution {
public:
    void dfs(vector<int> & v, vector<vector<int>>& M, int line) {
        for (int i = 0; i < M[line].size(); i++) {
            if (M[line][i] == 1 && v[i] == 0) {
                v[i] = 1;
                dfs(v, M, i);
            }
        }
    }
    int findCircleNum(vector<vector<int>>& M) {
        vector<int> v(M.size(), 0);
        int count = 0;
        for (int i = 0; i < M.size(); i++) {
            if (v[i] == 0) {                
                dfs(v, M, i);
                count++;
            }
        }
        return count;
    }
};

C++: BFS

class Solution {
public:
    int findCircleNum(vector<vector<int>>& M) {
        int n = M.size(), res = 0;
        vector<bool> visited(n, false);
        queue<int> q;
        for (int i = 0; i < n; ++i) {
            if (visited[i]) continue;
            q.push(i);
            while (!q.empty()) {
                int t = q.front(); q.pop();
                visited[t] = true;
                for (int j = 0; j < n; ++j) {
                    if (!M[t][j] || visited[j]) continue;
                    q.push(j);
                }
            }
            ++res;
        }
        return res;
    }
}; 

C++: Union Find

class Solution {
public:
    int findCircleNum(vector<vector<int>>& M) {
        UnionFind circles(M.size());
        for (int i = 0; i < M.size(); ++i) {
            for (int j = 0; j < M[i].size(); ++j) {
                if (M[i][j] && i != j) {
                    circles.union_set(i, j);
                }
            }
        }
        return circles.size();
    }

private:
    class UnionFind {
        public:
            UnionFind(const int n) : set_(n), count_(n) {
                iota(set_.begin(), set_.end(), 0);
            }

            int find_set(const int x) {
               if (set_[x] != x) {
                   set_[x] = find_set(set_[x]);  // Path compression.
               }
               return set_[x];
            }

            void union_set(const int x, const int y) {
                int x_root = find_set(x), y_root = find_set(y);
                if (x_root != y_root) {
                    set_[min(x_root, y_root)] = max(x_root, y_root);
                    --count_;
                }
            }

            int size() const {
                return count_;
            }

        private:
            vector<int> set_;
            int count_;
    };
};

C++: 并查集

struct DisjointSet{  
    int par;  
    int rank;  
};  
#define maxn 222  
struct DisjointSet ds[maxn];  
  
void init()  
{  
    for(int i = 0;i < maxn;i++){  
        ds[i].par = i;  
        ds[i].rank = 1;  
    }  
}  
  
int find(int x)  
{  
    if(x == ds[x].par) return  x;  
    return ds[x].par = find(ds[x].par);  
}  
  
void _union(int x, int y)  
{  
    x = find(x);  
    y = find(y);  
    if(x == y) return ;  
    if(ds[x].rank < ds[y].rank)  
        ds[x].par = y;  
    else{  
        if(ds[x].rank == ds[y].rank)  
            ds[x].rank++;  
        ds[y].par = x;  
    }  
}  
  
int same(int x, int y)  
{  
    return find(x) == find(y);  
}  
  
int findCircleNum(int** M, int MRowSize, int MColSize) {  
    init();  
    for(int i = 0;i < MRowSize;i++){  
        for(int j = i + 1;j < MColSize;j++){  
            if(M[i][j] && M[j][i]) _union(i,j);  
        }  
    }  
    int count = 0;  
    for(int i = 0;i < MRowSize;i++){  
        if(ds[i].par == i) count++;  
    }  
    return count;  
}  

  

    

类似题目:

[LeetCode] 323. Number of Connected Components in an Undirected Graph 无向图中的连通区域的个数

[LeetCode] 200. Number of Islands 岛屿的数量

[LeetCode] 305. Number of Islands II 岛屿的数量 II

 

All LeetCode Questions List 题目汇总

 

posted @ 2018-03-29 08:50  轻风舞动  阅读(2037)  评论(0编辑  收藏  举报