https://leetcode.com/problems/friend-circles/description/
class UnionFound { public: vector<int> v; int cnt; UnionFound(int n) { v = vector<int>(n); for (int i = 0; i < n; i++) v[i] = i; cnt = n; } int GetParent(int i) { if (v[i] == i) return i; return v[i] = GetParent(v[i]); } void Union(int p, int c) { int pp = GetParent(p); int cp = GetParent(c); if (pp != cp) { v[cp] = v[pp]; cnt--; } } }; class Solution { public: int findCircleNum(vector<vector<int>>& M) { int m = M.size(); if (m == 0) return 0; UnionFound uf(m); for (int i = 0; i < m; i++) for (int j = i+1; j < m; j++) if (M[i][j] == 1) uf.Union(i, j); return uf.cnt; } };