547. Friend Circles
There areNstudents in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is adirectfriend of B, and B is adirectfriend of C, then A is anindirectfriend of C. And we defined a friend circle is a group of students who are direct or indirect friends.
Given aN*NmatrixMrepresenting the friend relationship between students in the class. If M[i][j] = 1, then the ithand jthstudents aredirectfriends 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:
- N is in range [1,200].
- M[i][i] = 1 for all students.
- If M[i][j] = 1, then M[j][i] = 1.
Analysis:
Union find, in the end, loop through union find arr to see how many different "big brother" are there.
Complexity:
Time: O(N^2) since it takes N^2 times to detect whether 2 people are connected for N people in total. Union find connect complexity is only O(1) on average as we did the optimization for find();
Space: O(N) - the union find arr only need N size.
Code:
public class Solution {
private int[] friendCircle;
private int find(int x){
if(friendCircle[x] == x){
return x;
}
return friendCircle[x] = find(friendCircle[x]);
}
private void connect(int a, int b){
int acircle = find(a);
int bcircle = find(b);
if(acircle != bcircle){
friendCircle[acircle] = bcircle;
}
}
public int findCircleNum(int[][] M) {
if(M == null || M.length == 0){
return 0 ;
}
friendCircle = new int[M.length];
for(int i = 0; i < M.length; i++){
friendCircle[i] = i;
}
for(int i = 0; i < M.length - 1; i++){
for(int j = i + 1; j < M.length; j++){
if(M[i][j] != 0){
connect(i,j);
}
}
}
Set<Integer> returnSet = new HashSet<Integer>();
for(int i = 0; i < M.length; i++){
returnSet.add(find(friendCircle[i]));
}
return returnSet.size();
}
}