Formatted question description: https://leetcode.ca/all/547.html

547. Friend Circles (Medium)

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.

Companies:
Two Sigma, LinkedIn, Bloomberg, Microsoft

Related Topics:
Depth-first Search, Union Find

Similar Questions:

Solution 1. Union Find

// OJ: https://leetcode.com/problems/friend-circles/

// Time: O(N^2 * a(N)), where `a` is the inverse function of Ackermann function. O(a(N)) is faster than O(log(N)).
// Space: O(N)
class UnionFind {
private:
    vector<int> rank;
    vector<int> id;
    int count;
    int find (int i) {
        if (id[i] == i) return i;
        return id[i] = find(id[i]);
    }
public:
    UnionFind(int n) : rank(n, 0), id(n), count(n) {
        for (int i = 0; i < n; ++i) id[i] = i;
    }
    void connect(int i, int j) {
        int p = find(i), q = find(j);
        if (p == q) return;
        if (rank[p] > rank[q]) id[p] = q;
        else {
            id[q] = p;
            if (rank[p] == rank[q]) rank[p]++;
        }
        --count;
    }
    int getCount() { return count; }
};
class Solution {
public:
    int findCircleNum(vector<vector<int>>& M) {
        int N = M.size();
        UnionFind uf(N);
        for (int i = 0; i < N; ++i)
            for (int j = i + 1; j < N; ++j)
                if (M[i][j]) uf.connect(i, j);
        return uf.getCount();
    }
};

Solution 2. DFS

// OJ: https://leetcode.com/problems/friend-circles

// Time: O(N^2)
// Space: O(N)
class Solution {
private:
  void dfs(vector<vector<int>>& M, int i, vector<bool> &visited) {
    visited[i] = true;
    for (int j = i + 1; j < M.size(); ++j) {
      if (!M[i][j] || visited[j]) continue;
      dfs(M, j, visited);
    }
  }
public:
  int findCircleNum(vector<vector<int>>& M) {
    vector<bool> visited(M.size(), false);
    int cnt = 0;
    for (int i = 0; i < M.size(); ++i) {
      if (visited[i]) continue;
      dfs(M, i, visited);
      ++cnt;
    }
    return cnt;
  }
};

Java

class Solution {
    public int findCircleNum(int[][] M) {
        Map<Integer, Set<Integer>> friendsMap = new HashMap<Integer, Set<Integer>>();
        int studentsCount = M.length;
        for (int i = 0; i < studentsCount; i++) {
            Set<Integer> set = new HashSet<Integer>();
            set.add(i);
            friendsMap.put(i, set);
        }
        for (int i = 0; i < studentsCount; i++) {
            for (int j = i + 1; j < studentsCount; j++) {
                if (M[i][j] == 1) {
                    Set<Integer> set1 = friendsMap.getOrDefault(i, new HashSet<Integer>());
                    Set<Integer> set2 = friendsMap.getOrDefault(j, new HashSet<Integer>());
                    Set<Integer> unionSet = new HashSet<Integer>(set1);
                    unionSet.addAll(set2);
                    for (int student : unionSet)
                        friendsMap.put(student, unionSet);
                }
            }
        }
        int circles = 0;
        Set<Integer> totalSet = new HashSet<Integer>();
        for (int i = 0; i < studentsCount; i++) {
            if (!totalSet.contains(i)) {
                Set<Integer> set = friendsMap.getOrDefault(i, new HashSet<Integer>());
                totalSet.addAll(set);
                circles++;
            }
        }
        return circles;
    }
}

All Problems

All Solutions