#leetcode#547. Friend Circles
阿新 • • 發佈:2018-12-27
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 directfriends 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 1ststudents 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.
Two Sigma 的題,考察 Union Find, 和Number of islands ii 基本一樣
由於對稱性,只遍歷右上角的點就夠了,另外對角線上的點也可略過,直接把n加到結果裡面,然後沒發現需要union則 result--
union method犯了錯,應該把兩個點的root連線起來
public class Solution {
public int findCircleNum(int[][] M) {
int res = 0;
if(M == null || M.length == 0 || M[0].length == 0)
return res;
int n = M.length;
int[] roots = new int[n];
Arrays.fill(roots, -1); //here we init the roots array to current index itself, because M[i][i] = 1 for all students.
res = n;
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){//only top right half is enough to include all the cycles
if(M[i][j] != 1)
continue;
int rootI = findRoot(roots, i);
int rootJ = findRoot(roots, j);
if(rootI != rootJ){
// union(roots, i, j);
roots[rootJ] = rootI; //直接在這裡做union的操作了,否則union method中還要重複計算rootI,rootJ
res--;
}
}
}
return res;
}
private void union(int[] roots, int i, int j){//keep in mind that union is to union the roots of both position
// roots[j] = roots[i]; ERROR in union method!!!!!!!!!!!!!
// roots[j] = i;
int rootJ = findRoot(roots, j);
int rootI = findRoot(roots, i);
roots[rootJ] = rootI;
}
private int findRoot(int[] roots, int i){
if(roots[i] == -1)
return i;
int root = findRoot(roots, roots[i]);
roots[i] = root;
return root;
}
}