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.
统计朋友圈个数。
解决思路:用Union-Find做。初始化res等于总人数,index数组储存所属朋友圈,初始化每个人属于自己的朋友圈。如果两个人是朋友,首先Find,如果属于不同的朋友圈,就Union,且res减1。
class Solution { public: int Find(vector<int>& index, int i) { while(index[i]!=i) i = index[i]; return i; } void Union(vector<int>& index, int i1, int i2) { for(int i=0; i<index.size(); ++i) if(index[i]==i1) index[i] = i2; } int findCircleNum(vector<vector<int>>& M) { int len = M.size(); int res = len; vector<int> index; for(int l=0; l<len; ++l) index.push_back(l); int i,j; for(i=0; i<len; ++i) for(j=i+1; j<len; ++j) if(M[i][j] && Find(index, i)!=Find(index, j)) { --res; Union(index, Find(index, i), Find(index, j)); } return res; } };