Same idea. Just a little bit difference.

class Solution { int[] father; public class UnionFind { public UnionFind(int n) { for (int i = 1; i <= n; i++) { father[i] = i; } } public int find(int x) { if (father[x] == x) { return x; } return father[x] = find(father[x]); } public boolean query (int a, int b) { int x = find(a); int y = find(b); return x == y; } public void union (int a, int b) { int x = find(a); int y = find(b); if(x != y) { father[x] = y; } } } public int findCircleNum(int[][] M) { int n = M.length; father = new int[n + 1]; UnionFind uf = new UnionFind(n); int count = n; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if(M[i][j] == 1 && !uf.query(i, j)) { count--; uf.union(i,j); } } } return count; } }Friend Circles