Number of Friend Circles

Circle of Friends

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.

Problem Source: leetcode.com

Key Observation
The problem is to find connected components. This can be done using DFS or BFS.
Iterative approach is preferred over recursive ones usually.

class Solution {
public:
    int findCircleNum(vector<vector<int>>& M) {
        return circles(M);;
    }

    int circles(vector<vector<int>>& M) {
        auto N = M.size(); // peoples
        // BFS usually needs a queue
        queue<int> q;
        // to know visited person
        vector<bool> seen(N, false);
        int total_circles = 0;
        // each i is a person. start looking at the people he/she knows
        // and count one friend circle for all connected people through this
        // Think about it like layer by layer ie first look at all friends of i
        //, in next stage, look at these friends one by one.
        for (int i = 0; i < N; i++) {
            // already seen and looked at this person's friends?
            if (seen[i])
                continue;
            
            q.push(i);
            while (!q.empty()) {
                auto person = q.front();
                q.pop();
                seen[person] = true; // mark seen
                // lets add person's all friends to queue
                for (int j = 0; j < N; j++) {
                    if (M[person][j] && !seen[j])
                        q.push(j);
                }
            }
            // all connected people are processed, so bump up the circle
            total_circles += 1;
        }
        
        return total_circles;
    }
};

Published by Jeet

A software developer by profession. In spare time, fancy non-fiction mostly, related to history, finance and politics. A self-proclaimed movie buff - genre, time and era is no bar, only a sumptuous movie is!

Leave a comment